text
stringlengths
11
4.05M
package index import ( "math" "fmt" "strings" ) type Posting struct { docId int offsets []int termFrequency int } func (p Posting) String() string { return fmt.Sprintf("<DocId: %d, offsets:%v>", p.docId, p.offsets) } func NewPosting(docId int, offsets []int) *Posting { return &Posting{ docId...
package service import ( "encoding/json" "fmt" "io/mariomang/github/consts" "io/mariomang/github/domain" "io/mariomang/github/snowflake" ) func GenrateIDService(request *domain.RequestDomain) string { sf := snowflake.NewSnowFlake(request.WorkID, request.MachineID) id := sf.GetID() response, err := json.Marsha...
package keys import ( "fmt" "strings" "testing" sdktestutil "github.com/cosmos/cosmos-sdk/testutil" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/ovrclk/akcmd/testutil" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" s...
package server import ( "fmt" "github.com/superboy724/wechatmessage/processer" "io/ioutil" "net/http" "strconv" ) type Server struct { port int processer processer.Processer } func (t *Server) Run() { portStr := strconv.Itoa(t.port) http.HandleFunc("/", t.read) http.ListenAndServe(":"+portStr, nil) } ...
package bloom func (filter *Filter) Probe(key string) bool { hashedKey := [][]byte{} value := false; for _, fn := range filter.Functions { hashedKey = append(hashedKey, fn([]byte(key))) } for _, hashBytes := range hashedKey { halfArr := (len(hashBytes)/2)-1; part := 0; for j := 0; j <= halfArr; j++ { p...
package testdata import ( "github.com/frk/gosql" "github.com/frk/gosql/internal/testdata/common" ) type UpdateFromblockJoinSingleQuery struct { User *common.User4 `rel:"test_user:u"` From struct { _ gosql.Relation `sql:"test_post:p"` _ gosql.LeftJoin `sql:"test_join1:j1,j1.post_id = p.id"` _ gosql.RightJo...
package main import ( "bytes" "encoding/csv" "flag" "fmt" "io" "io/ioutil" "os" "text/template" ) var funcMap = template.FuncMap{ "repeat": func(ctr int) (r []int) { for i := 0; i < ctr; i++ { r = append(r, i) } return }, } func main() { var headerFileName, footerFileName, bodyFileName, dataFileN...
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ag...
package database import ( "reflect" "testing" "time" "github.com/ubclaunchpad/pinpoint/protobuf/models" ) func TestDatabase_AddNewUser_GetUser(t *testing.T) { type args struct { u *models.User e *models.EmailVerification } type errs struct { addUser bool getUser bool getVerify bool } tests := ...
package main import ( "errors" "fmt" ) func echo(request string) (string, error) { if request == "" { return "", errors.New("empty request") } return request, nil } func main() { requests := []string{"", "hello"} for _, r := range requests { if resp, err := echo(r); err != nil { continue } else { ...
package content import ( "errors" "fmt" ) type Ranger struct { numHunks int } func NewRanger(hunks int) Ranger { return Ranger{ numHunks: hunks, } } func (r Ranger) BuildRange(contentLength int64) ([]string, error) { if contentLength == 0 { return []string{}, errors.New("content length cannot be zero") }...
package 滑动窗口 const ( inf = 1000000000 ) func balancedString(s string) int { hash := make(map[uint8]int) hash['Q'], hash['W'], hash['E'], hash['R'] = 0, 1, 2, 3 wholeCount := make([]int, 4) // 字符串的字符信息 for i := 0; i < len(s); i++ { wholeCount[hash[s[i]]]++ } windowNeedCount := make([]int, 4) // 窗口所需要的字符信息 fo...
package http import ( "net" "net/http" ) func NewClient(options *Options) *http.Client { tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: options.Timeout, KeepAlive: options.KeepAlive, DualStack: options.DualStack, }).DialContext, TLSHandshakeTimeout:...
package oracle import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/irisnet/irismod/modules/oracle/keeper" "github.com/irisnet/irismod/modules/oracle/types" ) // NewHandler returns a handler for all the "oracle" type messages func NewHandler(k keeper...
package hub import ( "log" "strings" "sync" "github.com/desertbit/glue" "github.com/garyburd/redigo/redis" ) var ( sockets = map[*glue.Socket]map[string]bool{} topics = map[string]map[*glue.Socket]bool{} pubconn redis.Conn subconn redis.PubSubConn l sync.RWMutex ) func InitHub(url string) error { c, e...
package pn532 import ( "errors" ) var ( ErrAuthentificationFailed = errors.New("authentification failed") ) // Mifare Classic methods func MifareClassicIsFirstBlock(b uint32) bool { if b < 128 { return b%4 == 0 } return b%16 == 0 } func MifareClassicIsTrailerBlock(b uint32) bool { if b < 128 { return (b+1...
package entity type User struct { } func (u User) GetUserByID(id int32) { }
package entity import ( "github.com/google/uuid" ) type ForumThread struct { ID uuid.UUID `db:"id"` Title string `db:"title"` Description string `db:"description"` } type ForumPost struct { ID uuid.UUID `db:"id"` ThreadID uuid.UUID `db:"thread_id"` ThreadTitle string Title ...
package api import ( "crypto/tls" "fmt" "io" "math/rand" "net/http" "net/url" "os" "path/filepath" "sync" "time" "github.com/apex/log" "github.com/pkg/errors" "github.com/vbauerster/mpb/v4" "github.com/vbauerster/mpb/v4/decor" ) func getProxy(proxy string) func(*http.Request) (*url.URL, error) { ...
package main import ( "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "tesou.io/platform/brush-parent/brush-core/common/routers" ) func init() { router := &routers.MyRouter{} router.Hello() } func main() { beeRun() } func beeRun() { beego.LoadAppConfig("ini", "conf/app.conf") logs.SetLogger(logs...
package main import ( "fmt" ) const ( steps = 303 rounds = 2017 ) func main() { var cur int buffer := []int{0} for i := 1; i <= rounds; i++ { cur = (cur + steps) % len(buffer) + 1 buffer = append(buffer, 0) copy(buffer[cur+1:], buffer[cur:]) buffer[cur] = i } cur = (cur + 1) % len(buffer) fmt.Prin...
package suites import ( "context" "fmt" "net/http" "testing" "time" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "github.com/valyala/fasthttp" ) type HighAvailabilityWebDriverSuite struct { *RodSuite } func NewHighAvailabilityWebDriverSuite() *H...
package template type TestClass struct { PackageName string ImportNames []string Functions []*Function } type Function struct { FunctionName string FunctionReturns map[interface{}]string // key:type, value:name FunctionParams map[interface{}]string // key:type, value:name }
package main import ( "fmt" "math/rand" ) func main() { fmt.Println("Spaceline Company Days Round-trip Price") fmt.Println("=======================================") var distance = 57600000 var count = 0 for count < 10 { var speed = rand.Intn(15) + 16 // 16-30 km/s var duration = distance / spee...
package lmqtt import ( "github.com/lab5e/lmqtt/pkg/config" "github.com/lab5e/lmqtt/pkg/persistence/queue" "github.com/lab5e/lmqtt/pkg/persistence/session" "github.com/lab5e/lmqtt/pkg/persistence/subscription" "github.com/lab5e/lmqtt/pkg/persistence/unack" ) // NewPersistence creates a new persistence layer type ...
package Employee import ( "errors" "github.com/jinzhu/gorm" "html" "log" "strings" "time" "unicode" ) type Employee struct { Id uint32 `gorm:"primary_key;auto_increment" json:"id"` Name string `json:"name"` Address string `json:"address"` PhoneNumber string `json:"phone_numb...
// Copyright 2018 the Service Broker Project 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 applic...
// Copyright 2022 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 in wr...
// package db contains database related helper functions. The supported // databases (rdbms) are currently Firebird and MySQL. package db import "fmt" // DataPointers can be used for sql queries where you don't know the number of // columns to select. // // Usage: // // sqlStr := "SELECT C1, C2, Cn FROM table" // row...
package context import ( "os" "strconv" ) type ( // Конфигурация Configuration struct { PsqlConfiguration *PsqlConfiguration ServerConfiguration *ServerConfiguration } // Конфигурация БД PsqlConfiguration struct { Host string Port string User string Password string DbName string ...
package main import ( "fmt" . "github.com/smartystreets/goconvey/convey" "gopkg.in/redis.v3" "os" "testing" "time" ) // TestRedis tests all of features of the redis interface. func TestRedis(t *testing.T) { Convey("The Redis interface tests, ", t, func() { Convey("Without a REDIS_URL", func() { curVal := ...
package sort import "fmt" // MaxK return the kth max number in a numbers array func MaxK(nums []int, k int) int{ return _maxK(nums, 0, len(nums)-1, k-1) } func _maxK(nums []int, p int, r int, k int) int { if k > r || k < p{ return -1 } //分区 q := p for i := p; i <= r; i++ { if nums[i] > nums[r] { nums[i]...
package main import ( "encoding/hex" "encoding/json" "log" "reflect" "strconv" "github.com/ugorji/go/codec" ) type Item struct { Ref Ref `json:"ref"` Size uint32 `json:"size"` Compression uint8 `json:"compr,omitempty"` OSize uint32 `json:"osize,omitempty"` } type Ref struct { Typ...
package problem0189 func rotateNewPlace(nums []int, k int) { size := len(nums) newNums := make([]int, size) for i := 0; i < size; i++ { newNums[(i+k)%size] = nums[i] } copy(nums, newNums) } func rotate(nums []int, k int) { size := len(nums) k = k % size reverse(nums, 0, size-1) reverse(nums, 0, k-1) rever...
package ciolite // Api functions that support: webhooks import ( "fmt" ) // GetWebhooks gets listings of Webhooks configured for the application. func (cioLite CioLite) GetWebhooks() ([]GetUsersWebhooksResponse, error) { // Make request request := clientRequest{ Method: "GET", Path: "/lite/webhooks", } ...
package queries import ( "log" "github.com/jmoiron/sqlx" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes/models" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" ) const GET_FACTOR_ATTRIBUTE_BY_ID_SQL = ` SELECT a."AttributeId" ,a."AttributeEnumId" ,a...
package flagen import "strconv" type value interface { set(string) error Get() interface{} Type() string } func newBoolValue(v string) (*boolValue, error) { bv := &boolValue{} err := bv.set(v) return bv, err } type boolValue struct { v bool } func (b *boolValue) set(s string) error { v, err := strconv.Pars...
// 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 ( log "github.com/sirupsen/logrus" "sync" "time" ) func Foo(wg *sync.WaitGroup) { defer wg.Done() log.Info("Foo is starting!") for i := 0; ; i++ { log.Debugf("Foo is doing thing %d", i) if i == 5 { log.Warn("Foo is 1/2 done!") } if i > 5 { log.Error("Uh-oh, I have a problem!") ...
package cart import ( "context" "github.com/gingerxman/eel" "github.com/gingerxman/ginger-product/business" ) type CartRepository struct { eel.RepositoryBase } func NewCartRepository(ctx context.Context) *CartRepository { repository := new(CartRepository) repository.Ctx = ctx return repository } //GetShipInf...
/* Copyright 2011 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 di...
package attachments import ( "bufio" "bytes" "errors" "io" "os" "github.com/keybase/client/go/chat/globals" "github.com/keybase/client/go/libkb" "github.com/keybase/client/go/protocol/chat1" "github.com/keybase/client/go/protocol/gregor1" "golang.org/x/net/context" ) func AssetFromMessage(ctx context.Conte...
package main import ( "fmt" "os" "github.com/vlad-belogrudov/gopl/pkg/reverse" ) func main() { if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "need string to revert") os.Exit(1) } bytes := []byte(os.Args[1]) if err := reverse.RevertUTF8Bytes(bytes); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) ...
/* Copyright (c) 2017 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions...
package client import ( "crypto" "github.com/go-acme/lego/v3/certificate" "github.com/alphatr/acme-lego/common/errors" ) // CertificateObtain 证书获取 func (cli *Client) CertificateObtain(domains []string, secret crypto.PrivateKey) (*certificate.Resource, *errors.Error) { request := certificate.ObtainRequest{ Dom...
package middleware import ( "context" "encoding/json" "errors" "github.com/bitmaelum/bitmaelum-suite/internal" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/gorilla/mux" "github.com/sirupsen/logrus" "github.com/vtolstov/jwt-go" "net/h...
package randomutils import ( "math/rand" "time" ) func RandomStringByPattern(pattern []byte, n int) string { result := []byte{} r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < n; i++ { result = append(result, pattern[r.Intn(len(pattern))]) } return string(result) } func RandomString(n i...
package run import floc "gopkg.in/workanator/go-floc.v1" /* Parallel runs jobs in their own goroutines and waits until all of them finish. Summary: - Run jobs in goroutines : YES - Wait all jobs finish : YES - Run order : PARALLEL Diagram: +-->[JOB_1]--+ | | --+--> .. --+--...
package CpUtil // 求解器常用函数和常量 const BITSIZE = 64 const DIVBIT = 6 const MODMASK = 0x3f const INDEXOVERFLOW = -1 const ALLONELONG = 0xFFFFFFFFFFFFFFFF const ALLONE64 = 0xFFFFFFFFFFFFFFFF const INTMAXINF = 0x3f3f3f3f const INTMININF = -0x3f3f3f3f const LONGMAXINF = 0x3f3f3f3f3f3f3f3f const LONGMININF = -0x3f3f3f3f3f3f3f...
package controller import ( "go-gin-start/app/util" "time" "github.com/gin-gonic/gin" ) type Index struct{} /** * Index **/ func (Index) Index(c *gin.Context) { // return c.JSON(200, gin.H{ "create_at": util.FirstIni.Section("").Key("created_at").String(), "server_time": time.Now(), }) }
package handlers import ( "hilfling-oauth/database" "net/http" "github.com/gin-gonic/gin" ) type securityLevel struct { Id int `json:"id" binding:"required"` Level string `json:"level" binding:"required"` } func getSecurityLevels() ([]securityLevel, error) { const q = `SELECT * FROM security_level;` ro...
package main import ( "fmt" "net/http" "github.com/wlMalk/gapi" "github.com/wlMalk/gapi/constants" "github.com/wlMalk/gapi/operation" "github.com/wlMalk/gapi/param" "github.com/wlMalk/gapi/request" "github.com/julienschmidt/httprouter" wrapper "github.com/wlMalk/gapi/wrapper/julienschmidt/httprouter" ) fun...
package main import "fmt" var strList []string var numList []string var numListEmpty = []int{} // 已被分配内存, 所以不等于nil func main() { fmt.Println(strList, numList, numListEmpty) fmt.Println(len(strList), len(numListEmpty), len(numList)) fmt.Println(strList == nil) fmt.Println(numList == nil) fmt.Println(numListEmpt...
/** Create a slice of a slice of string. Store the following data in the multi-dimensional slice: - "James", "Bond", "Shaken, not stirred" - "Miss", "Moneypenny", "Hellooooooo, James." Range over the records, then range ove the data in each record */ package main import ( "fmt" ) func main() { slice1...
//Package prototests contains some structures and values that are useful for testing the protocol buffer parser. package prototests
package api import ( "encoding/json" "fmt" "html/template" "github.com/mpolden/ipd/useragent" "github.com/sirupsen/logrus" "math/big" "net" "net/http" "path/filepath" "strconv" "strings" "github.com/gorilla/mux" ) const ( jsonMediaType = "application/json" textMediaType = "text/plain" ) type API str...
package modules import ( "../../domain/repository" serviceModule "../../services" ) type ServiceModule interface { LoadServices(kpr repository.IKubePodRepository) *serviceModule.IKubeService } func LoadServices(kpr repository.IKubePodRepository) serviceModule.IKubeService { var kubeService = serviceModule.InitKu...
package draw type RectangleGraphic struct { rect Rectangle Style RectangStyle childs []IGraphic parent IGraphic text *Text } type RectangStyle struct { Level int DrawBorder bool DoFill bool FillColor Color BorderColor Color BorderWidth int } func (this *RectangleGraphic) Draw(canvas ICa...
/* * @lc app=leetcode.cn id=1325 lang=golang * * [1325] 删除给定值的叶子节点 */ // @lc code=start /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ // package leetcode // type TreeNode struct{ // Val int // Left *TreeNode // Right...
package api import ( "context" "fmt" "net/http" "time" ) type config struct { Port uint `json:"port"` CreaturesPath string `json:"creatures_path"` } type ShutdownFunc func(context.Context) error func Serve(configPath string) (error, <-chan error, ShutdownFunc) { conf, err := readConfig(conf...
package Services_GIS import ( . "Framework/Framework_Definitions" ) // ------------------------------------------- Definitions ------------------------------------------- // // To create new services, in a new file create a struct and implement the methods found in ServiceInterface in ServiceInterface.go // All ser...
package middleware import ( "net/http" ) // PrettyJSON is a middleware that will set a response header based on the request URI. This can be used to output // json data either indented or not. type PrettyJSON struct { http.ResponseWriter } // Middleware sets header based on query param func (*PrettyJSON) Middlewar...
package main import ( "errors" "fmt" "math" "os" "path/filepath" "github.com/gitchander/go-lang/cairo" "github.com/gitchander/go-lang/cairo/color" ) const ( textureDefiance1 = "./images/defiance1.png" textureDefiance2 = "./images/defiance2.png" textureChippedBricks = "./images/chipped-bricks.png" ...
package fibonacci import ( "testing" ) func TestFibonacci(t *testing.T) { want := 55 got := Fibonacci(10) if got[10] != want { t.Fatalf("expectation: %d\nreality: %d", want, got) } }
// https://www.hackerrank.com/challenges/balanced-parentheses package main import ( "bufio" "fmt" "os" ) func main() { var t int _, err := fmt.Scan(&t) if err == nil { scanner := bufio.NewScanner(os.Stdin) testCases := make([]string, t) for i := 0; i < t; i++ { if !scanner.Scan() { break } te...
package models import ( "fmt" "github.com/kjirou/tower-of-go/utils" "testing" "time" "strings" ) func TestField_At_NotTD(t *testing.T) { field := createField(2, 3) t.Run("指定した位置の要素を取得できる", func(t *testing.T) { element, _ := field.At(&utils.MatrixPosition{Y: 1, X: 2}) if element.GetPosition().GetY() != 1 {...
package config import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/pkg/policy" "github.com/pomerium/pomerium/pkg/policy/parser" ) func TestPolicy_ToPPL(t *testing.T) { str, err := policy.GenerateRegoFromPolicy((&Policy{ AllowPublicUnaut...
package exception //go:generate go install github.com/Beyond-simplechain/foundation/log //go:generate go install github.com/Beyond-simplechain/foundation/exception //go:generate gotemplate -outfmt "gen_%v" "github.com/Beyond-simplechain/foundation/exception/template" "StdException(Exception,StdExceptionCode,\"golang s...
package parser import ( "github.com/PuerkitoBio/goquery" "spider/entity" ) type Parser interface { ConnectDocument(target string) *goquery.Selection //连接爬取页面,并设置css选择器 SelectorService(i int, selection *goquery.Selection) //处理经过css选择器筛选后的元素 GetDocInfo() []entity.JobInfo //返回爬取信息 }
package dbsrv import ( "os" "time" "gopkg.in/doug-martin/goqu.v3" "github.com/empirefox/esecend/front" "github.com/empirefox/reform" ) func (dbs *DbService) WishlistSave(userId uint, payload *front.WishlistSavePayload) (*front.WishItem, error) { data := &front.WishItem{ UserID: userId, CreatedAt: time....
package routers import ( "errors" "io/ioutil" "net/http" "regexp" "strconv" "github.com/gin-gonic/gin" "github.com/vpakhuchyi/web-server/models" ) //POSTJSONHandler is a POST handler for "/searchText"; //it checks incoming JSON and sends a result of "searchForArgsOnEachSite" func as JSON response. func POSTJ...
package influxdb import ( "encoding/json" "math" "regexp" "sort" "strings" "time" "github.com/boltdb/bolt" "github.com/influxdb/influxdb/influxql" ) // database is a collection of retention policies and shards. It also has methods // for keeping an in memory index of all the measurements, series, and tags in...
package main import ( "fmt" "math/big" "github.com/jackytck/projecteuler/tools" ) func count(limit int) int { var cnt int d := big.NewInt(3) n := big.NewInt(2) for i := 1; i < limit; i++ { p := big.NewInt(0) p.Set(n) n.Add(d, n) d.Add(n, p) if len(tools.DigitsBig(d)) > len(tools.DigitsBig(n)) { c...
package chapter3 import ( "net/http" "fmt" "html" "io/ioutil" ) func init() { fmt.Println("=== Web Operation ====") listen() } func listen() { resp, err := http.Get("http://www.google.com") if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println(string(b...
package persist_lib func AmazingUniarySelectQuery(tx Runable, req AmazingUniarySelectQueryParams) *Result { row := tx.QueryRow( "SELECT * from example_table Where id=$1 AND start_time>$2 ", req.GetId(), req.GetStartTime(), ) return newResultFromRow(row) } func AmazingUniarySelectWithHooksQuery(tx Runable, req...
package main import ( "log" "net" "google.golang.org/grpc/reflection" "golang.org/x/net/context" pb "./public" "google.golang.org/grpc" data "./data" core "./core" "sort" "flag" ) var ( indexFile = flag.String("index", "", "the index cid file") dictFile = flag.String("dict", "", "the dict cid file") ) ty...
package main import "fmt" //testType is test type type testType struct { a int b string } //String string func for print func (t *testType) String() string { return fmt.Sprint(t.a) + " " + t.b } func main() { //init testType t := &testType{77, "Sunset Strip"} //print testType fmt.Println(t) }
package minnow type ProcessorPool struct { processor Processor runRequestQueue chan RunRequest } func NewProcessorPool(processor Processor, poolSize int) *ProcessorPool { runRequestQueue := make(chan RunRequest, 100*poolSize) for i := 0; i < poolSize; i++ { go processor.Run(runRequestQueue) } return &...
// Copyright (c) 2018-2020 Double All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package captcha import ( "net/http" "strconv" "github.com/2637309949/bulrush" "github.com/gin-gonic/gin" "github.com/mojocn/base64Captcha" ) // Captcha ...
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package redis import ( "time" "github.com/gogo/protobuf/proto" "storj.io/storj/protos/overlay" ) const defaultNodeExpiration = 61 * time.Minute // OverlayClient is used to store overlay data in Redis type OverlayClient struct { DB ...
package main import ( "basic-rabbitmq/RabbitMQ" "fmt" ) func main() { // Subscriber 02 rabbitmq := RabbitMQ.NewRabbitMQPubSub("newProduct") fmt.Println("Subscriber 02 start listening...") rabbitmq.RecieveSub() }
package tgo import ( "sync" ) var ( cacheConfigMux sync.Mutex cacheConfig *ConfigCache ) type ConfigCache struct { Redis ConfigCacheRedis RedisP ConfigCacheRedis // 持久化Redis Dynamic ConfigCacheDynamic } type ConfigCacheRedis struct { Address []string Prefix string Expire int...
package rados /* #cgo LDFLAGS: -lrados #include "stdlib.h" #include "stdint.h" #include "rados/librados.h" #include "libradosext.h" */ import "C" import ( "time" "unsafe" ) // Sub-read operation. type SubReadOperation interface { resolve() Release() } // Stat read sub-operation. type StatReadOperation struct...
package netgo import ( "fmt" "io" "io/ioutil" "log" "net/http" "os" "time" ) type Logger interface { Printf(string, ...interface{}) } // Client represents http client type Client struct { Inner *http.Client Logger Retry } // NewClient represents new http client func NewClient() *Client { return defaultC...
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw...
/* * @lc app=leetcode.cn id=237 lang=golang * * [237] 删除链表中的节点 */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } var head *ListNode func main() {...
// Package powervs extracts Power VS metadata from install configurations. package powervs import ( "context" icpowervs "github.com/openshift/installer/pkg/asset/installconfig/powervs" "github.com/openshift/installer/pkg/types" "github.com/openshift/installer/pkg/types/powervs" ) // Metadata converts an install ...
//////////////////////////////////////////////////////////////////////////////// // // // Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or // // its subsidiaries. ...
package nginxClient import ( "fmt" "io/ioutil" "net/http" "strconv" "strings" ) // NginxClient allows you to fetch NGINX metrics from the stub_status page. type NginxClient struct { apiEndpoint string httpClient *http.Client } // StubStats represents NGINX stub_status metrics. type StubStats struct { Connec...
package config import ( "testing" ) func TestIniFile(t *testing.T) { iniconf, err := NewConfig(IniProtocol, "config.ini") if err != nil { t.Fatal(err) } if name := iniconf.GetString("server.name"); name != "testserver" { t.Errorf("server.name = %s", name) } if name := iniconf.GetString("server.namedef", ...
package main import ( "context" "fmt" "io" "log" "os" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" docker "github.com/docker/docker/client" dotenv "github.com/joho/godotenv" amqp "github.com/streadway/amqp" ) // LogPublisher A io.Writer implementation to write data t...
package csrf import ( "errors" "net/textproto" "strings" "time" "github.com/gofiber/fiber/v2" ) // New creates a new middleware handler func New(config ...Config) fiber.Handler { // Set default config cfg := configDefault(config...) // Create manager to simplify storage operations ( see manager.go ) manage...
package Home import ( "encoding/json" "fmt" "github.com/gin-gonic/gin" "net/http" "webchat/Controller/Base" ) type IndexController struct { this Base.BaseController } /** 当前登录用户列表 */ type userList struct { Code int `json:"code"` Msg string `json:"msg"` Data userData `json:"data"` } /** 用户信息 */ type u...
package main // 坐标结构体 type Node struct { x, y int } var dx []int // x变化向量 var dy []int // y变化向量 var hasBeenHandled map[int]bool // 用于记录节点是否被处理过 // BFS调用者 func updateMatrix(matrix [][]int) [][]int { if len(matrix) == 0 { return matrix } hasBeenHandled = make(map[int]bool) /* 1. 确定搜索方向dx、dy */ dx = []int{0,...
package generate const LINKER_TEMPLATE = `package no.fint.consumer.models.{{ modelPkg .Package }}{{ ToLower .Name }}; import {{ resourcePkg .Package }}.{{ .Name }}Resource; import {{ resourcePkg .Package }}.{{ .Name }}Resources; import no.fint.relations.FintLinker; import org.springframework.stereotype.Compon...
// Package conf provides all functionality required for parsing and accessing // configuration files. // You can use a hjson/json/env files as configurations and access them recursively // with dots package conf import ( "flag" "fmt" "github.com/hjson/hjson-go" "github.com/joho/godotenv" "io/ioutil" "os" "path/...
package main import ( "fmt" "sort" ) func sum(a, b int) int { // Return type put after the parameters return a + b } func meanAndMedian(n ...float64) (float64, float64) { // Ellipsis to define listed inputs. Function returns tuple total := 0.0 for _, v := range n { // range keyword iterates through will tuple t...
package other import ( "fmt" "testing" ) func TestJinZhiConversion(t *testing.T) { Conversion(1348, 2) Conversion(1348, 8) Conversion(1348, 16) } /** @param n : 要转换的数值 @param d : 要转换成的进制数 */ func Conversion(n int, d int) { var stack []int for n != 0 { stack = append(stack, n%d) n /= d } // 输出 START f...
package logs import ( "encoding/json" "fmt" "log" "os" "strings" "sync" "time" ) const ( dateFmt string = "2006-01-02" dateTimeFmt string = "2006-01-02-15-04-05" //1M的大小 msize = 1048576 ) type MutexFileWriter struct { sync.Mutex fd *os.File } func (this *MutexFileWriter) SetFd(fd *os.File) { if th...
package log import ( "sync" ) var levelMap = make(map[string]int) var appLogger *Logger var once = sync.Once{} func init() { levelMap["DEBUG"] = 1 levelMap["INFO"] = 2 levelMap["WARN"] = 3 levelMap["ERROR"] = 4 appLogger = newStdoutLogger("DEBUG") } func InitAppLogger(path string, level string) { once.Do(fu...