text
stringlengths
11
4.05M
package xmltogo_test import ( //"../clouseau/reckon" "./" "encoding/xml" "fmt" //"io/ioutil" "reflect" "testing" ) func Test(t *testing.T) { /* bytes, err := ioutil.ReadFile("./data.xml") if err != nil { panic(err) } */ bytes := []byte("<a><b value=\"1\"/><c value=\"2\"/><d value=\"3\"/></a>") a :...
package versions import "github.com/galaco/bsp/lumps" func GetLumpForVersion(bspVersion int, lumpId int) (lumps.ILump, error) { switch bspVersion { case 19: return Getv19Lump(lumpId) case 20: return Getv20Lump(lumpId) case 21: return Getv21Lump(lumpId) default: return &lumps.Unimplemented{}, nil } }
package fs import "github.com/kamilsk/stream" func New(path string) *Storage { // check path is writable return &Storage{path: path} } type Storage struct { path string } func (s *Storage) Store(src stream.Source) error { if _, ok := src.(stream.Aggregator); ok { // handle aggregator } // handle entity ret...
// Copyright 2019 - 2022 The Samply Community // // 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 ...
package welcome import ( "net/http" "github.com/gin-gonic/gin" ) func Welcome(c *gin.Context) { c.HTML(200, "welcome", gin.H{ "title": "Introduce to Orchid", }) } func About(c *gin.Context) { c.HTML(200, "about", gin.H{ "title": "About", }) } func WelcomeApi(c *gin.Context) { c.JSON(http.StatusOK, gin.H...
package main import ( "fmt" "net/http" ) func (s *Instance) bindRoutes() { s.router.HandlerFunc("POST", "/play", s.handlePlay()) s.router.HandlerFunc("POST", "/stop", s.handleStop()) s.router.HandlerFunc("GET", "/list", s.handleList()) } func (s *Instance) handlePlay() http.HandlerFunc { return func(w http.Res...
package http import ( "ghitub/julhan07/redis-go/controllers" "github.com/go-redis/redis/v8" "github.com/gorilla/mux" ) func RunApp(r *mux.Router, redis *redis.Client) *mux.Router { user := controllers.NewUserController(redis) r.HandleFunc("/user/list", user.GetAll).Methods("GET") return r }
package rpterr import ( "fmt" "os" ) // ReportError reports an internal progam error func ReportError(err error) { // I'm using Fprintf here insted of log to make it really clear that // this isn't a log fmt.Fprintf(os.Stderr, "error: %s\n", err) }
package main // Leetcode 38. (easy) func countAndSay(n int) string { res := []byte{'1'} for i := 1; i < n; i++ { tmp := []byte{} for j := 0; j < len(res); j++ { cnt := 1 for j+1 < len(res) && res[j] == res[j+1] { cnt++ j++ } tmp = append(tmp, byte(cnt+'0'), res[j]) } res = tmp } return ...
package business import ( "encoding/json" "errors" "fmt" "strings" "sync" errors2 "k8s.io/apimachinery/pkg/api/errors" "github.com/kiali/kiali/config" "github.com/kiali/kiali/kubernetes" "github.com/kiali/kiali/log" "github.com/kiali/kiali/models" "github.com/kiali/kiali/prometheus/internalmetrics" ) typ...
package mgr import ( "log" "math/rand" "testing" "github.com/stretchr/testify/require" ) func TestHistogramMean(t *testing.T) { h := NewHistogram("foobar", 10000) for i := int64(0); i < 10000; i++ { h.Record(2) } require.Equal(t, int64(10000), h.counter) h.takeSnapshot() require.Equal(t, 2.0, h.mean())...
package main //2055. 蜡烛之间的盘子 //给你一个长桌子,桌子上盘子和蜡烛排成一列。给你一个下标从 0开始的字符串s,它只包含字符'*' 和'|',其中'*'表示一个 盘子,'|'表示一支蜡烛。 // //同时给你一个下标从 0开始的二维整数数组queries,其中queries[i] = [lefti, righti]表示 子字符串s[lefti...righti](包含左右端点的字符)。对于每个查询,你需要找到 子字符串中在 两支蜡烛之间的盘子的 数目。如果一个盘子在 子字符串中左边和右边 都至少有一支蜡烛,那么这个盘子满足在 两支蜡烛之间。 // //比方说,s = "||**||**|*",查询[3, ...
package usecase import ( "fmt" "marketplace/ads/domain" "github.com/go-pg/pg/v10" ) type DeleteAllMyAdsCmd func (db *pg.DB, user *domain.Account) (error) func DeleteAllMyAds() DeleteAllMyAdsCmd { return func (db *pg.DB, user *domain.Account) (error) { ads := domain.Ads{} res, err := db.Model(&ads).Where("a...
package main import ( "github.com/01-edu/z01" ) func putQueen(positions []int, row int, size int) { if row == size { printAns(positions, size) } else { for col := 0; col < size; col++ { if checkPlace(positions, row, col) { positions[row] = col putQueen(positions, row+1, size) } } } } func chec...
package validator import ( "github.com/yannh/kubeconform/pkg/registry" "testing" "github.com/yannh/kubeconform/pkg/resource" ) type mockRegistry struct { SchemaDownloader func() ([]byte, error) } func newMockRegistry(f func() ([]byte, error)) *mockRegistry { return &mockRegistry{ SchemaDownloader: f, } } f...
package utils import ( "bytes" "crypto/md5" "fmt" "io" "julian/goFileConvert/utils/file" "log" "math/rand" "net/http" "net/url" "os" "os/exec" "path" "runtime" "sort" "strings" "time" ) func ComparePath(a string, b string) bool { if len(a) >= len(b) { if strings.Compare(a[0:len(b)], b) == 0 { re...
package dbRepo import ( "fmt" "strings" "github.com/hariprathap-hp/bookstore_oauth_api/src/dbPostgres" "github.com/hariprathap-hp/bookstore_oauth_api/src/domain/token" "github.com/hariprathap-hp/bookstore_users_api/src/utils/errors" ) type DbRepository interface { GetAccessToken(string) (*token.AccessToken, *e...
package deploy import ( "context" "testing" config2 "github.com/loft-sh/devspace/pkg/devspace/config" devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context" "github.com/loft-sh/devspace/pkg/devspace/config/constants" "github.com/loft-sh/devspace/pkg/devspace/config/localcache" "github.com/loft-sh/...
/** * (C) Copyright IBM Corp. 2021. * * 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 agree...
package users import ( "testing" "time" "github.com/google/uuid" "github.com/jrapoport/gothic/core/tokens" "github.com/jrapoport/gothic/models/types" "github.com/jrapoport/gothic/models/types/key" "github.com/jrapoport/gothic/models/types/provider" "github.com/jrapoport/gothic/models/user" "github.com/jrapop...
package core import ( "fmt" "github.com/boltdb/bolt" "github.com/lunny/log" ) // 区块链数据结构: 切片 type BlockChain struct { tip []byte Db *bolt.DB } type BlockChainIterator struct { currentHash []byte Db *bolt.DB } const ( dbFile = "blockchain.db" blockBucket = "blocks" ) // 创世纪区块 func NewBlockCh...
// Copyright 2017 Walter Schulze // // 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 publisher import ( vaultapi "github.com/hashicorp/vault/api" ) type secretsStore interface { Keys() []string Get(string) (string, error) } func New(vault *vaultapi.Logical, path string) *Publisher { return &Publisher{ vault: vault, path: path, } } type Publisher struct { vault *vaultapi.Logical p...
package database import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" //postgres/sqlite3 "os" ) // Open returns a DB reference for a data source. func Connect() *gorm.DB { driverName := os.Getenv("DATABASE_DRIVER") connection := "" //check database driver //Note: This not a good practice....
package leetcode func majorityElement(nums []int) int { emap := make(map[int]int) var me int for i := 0; i < len(nums); i++ { _, ok := emap[nums[i]] if ok { emap[nums[i]] += 1 } else { emap[nums[i]] = 1 } } for k, v := range emap { if v > len(nums)/2 { me = k } } return me } // 进阶 时间复杂度O(...
package amqppool import ( "errors" "fmt" "github.com/streadway/amqp" "log" ) //Pool represents a connection and manage the pool of reusable channels type Pool struct { connection *amqp.Connection //the connection amqp maxChannels int //the maximum qu...
package rcache import ( "bytes" "github.com/astaxie/beego/context" "github.com/boltdb/bolt" "log" ) type Resource struct { Key []byte Value []byte } var ( ResourceChan chan Resource ) var ( DBResource = []byte("resource") ) var db *bolt.DB func init() { ResourceChan = make(chan Resource, 32) var err...
package web import ( "errors" "github.com/asdine/storm" "github.com/gin-gonic/gin" "github.com/smartcontractkit/chainlink/services" "github.com/smartcontractkit/chainlink/store/models" "github.com/smartcontractkit/chainlink/store/presenters" ) // AssignmentsController manages Assignment requests. type Assignme...
// Copyright (C) 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 t...
package constants const RedisHost = "localhost" const RedisPort = "6379" const RedisPass = "" const RedisDBId = 0 const RedisErrorCode = 2 const RedisErrorUnknownTypeCode = 3 const CalibrationErrorJsonMarshall = 4 const OffsetKey = "offset" const IdListKey = "ids_list" const CalibratedKey = "calibration_done" const C...
package gitreceive import ( "bytes" "context" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "testing" "github.com/arschles/assert" "github.com/docker/distribution/registry/storage/driver/factory" _ "github.com/docker/distribution/registry/storage/driver/inmemory" builderconf "github.com/teamh...
package appErrors import "net/http" type ErrorResponse struct { Status int `json:"status"` Message string `json:"message"` } func (e *ErrorResponse) Error() string { return e.Message } func (e *ErrorResponse) StatusCode() int { return e.Status } func DefaultBadRequest(message string) ErrorResponse { retur...
package main import ( "context" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/appsync" "log" "os" "time" ) func main(){ // On Lam...
package main import ( _ "hrefs.cn/src" "hrefs.cn/src/api" "hrefs.cn/src/srv" "hrefs.cn/src/web" ) func main() { go api.Start() go web.Start() srv.Start() }
package handlers import ( "log" "net/http" "os" "github.com/gorilla/mux" "github.com/rs/cors" "github.com/Estiven9644/twittor-backend/middlewares" "github.com/Estiven9644/twittor-backend/routers" ) func Manejadores() { router := mux.NewRouter() //manejar el http router.HandleFunc("/registro", middlewares....
package gameloop import ( fb "github.com/google/flatbuffers/go" ) type PacketWriter struct { positions map[uint32]Vector3 } func NewPacketWriter() *PacketWriter { return &PacketWriter{map[uint32]Vector3{}} } func (pw *PacketWriter) AppendPos(id uint32, v Vector3) { pw.positions[id] = v } func (pw *PacketWr...
package main import ( // "fmt" // "io/ioutil" "os" "os/exec" ) func main() { echo := exec.Command("echo", "hello") ruby := exec.Command("ruby", "pipe.rb") ruby.Stdin, _ = echo.StdoutPipe() ruby.Stdout = os.Stdout echo.Start() ruby.Start() ruby.Wait() echo.Wait() //-------------------------------------...
package main import ( "fmt" "github.com/veandco/go-sdl2/sdl" ) const ( screenWidth = 800 screenHeight = 600 ) func main() { fmt.Println("---------- STARTING APPLICATION 🏃----------") fmt.Println(" -> INITIALIZING SDL 🌏 ..............") if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil { fmt.Println("...
package solutions import ( "sort" ) func reconstructQueue(people [][]int) [][]int { sort.Slice(people, func (i int, j int) bool { if people[i][0] == people[j][0] { return people[i][1] < people[j][1] } return people[i][0] > people[j][0] }) result := make([][]int, l...
package repl import "io" type State struct { Continuation bool Inputs []string next int } func NewState() *State { return &State{ Continuation: false, Inputs: make([]string, 0, 1), next: 0, } } func (s *State) Readline() ([]byte, error) { if s.next >= len(s.Inputs) { s.next...
package main import ( "fmt" "unsafe" ) /* Pointer类型用于表示任意类型的指针。有4个特殊的只能用于Pointer类型的操作: 1) 任意类型的指针可以转换为一个Pointer类型值 2) 一个Pointer类型值可以转换为任意类型的指针 3) 一个uintptr类型值可以转换为一个Pointer类型值 4) 一个Pointer类型值可以转换为一个uintptr类型值 Sizeof返回类型v本身数据所占用的字节数。返回值是“顶层”的数据占有的字节数。例如,若v是一个切片,它会返回该切片描述符的大小,而非该切片底层引用的内存的大小。 Alignof返回类型v的对齐方式(即类型v...
package leetcode_go func minPathSum(grid [][]int) int { if len(grid) == 0 { return 0 } row, column := len(grid)-1, len(grid[0])-1 dp := make([][]int, row+1) for i := range dp { dp[i] = make([]int, column+1) } for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[0]); j++ { if i == 0 && j == 0 { ...
package nettest import ( "github.com/alecthomas/kingpin" "github.com/apex/log" "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/cli/root" "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/database" "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/output" ) func init() { cmd := root.Command("show", "S...
package config import ( "os" "path" "github.com/jinzhu/configor" ) // Config contains application configuration var Config = struct { Port uint `default:"1024" env:"PORT"` DataBase DataBase Redis Redis Env string `default:"test" env:"APP_ENV"` BaseSecret string `d...
package host import ( "errors" ) // MissingProfileError when the profile is mandatory var MissingProfileError = errors.New("missing profile name") // DefaultProfileError when trying to edit default content var DefaultProfileError = errors.New("'default' profile should not be handled by hostctl") // MissingDomainsE...
package cache // Cache represents the operations our // caching functionality must support type Cache interface { GetSeverity(finding string) (string, bool) }
package resolvers import ( "testing" "github.com/GibJob-ai/GObjob/db" "github.com/GibJob-ai/GObjob/model" ) func TestSignIn(t *testing.T) { db, err := db.ConnectDB() defer db.DB.Close() if err != nil { t.Errorf(err.Error()) } user := model.User{} db.DB.Where("email = ?", "notexisting@test.com").First(&u...
package main import ( "fmt" ) const ( x= iota // x == 0 y=iota // y == 1 z=iota // z == 2 w // 常量声明省略值时,默认和之前一个值的字面相同。这里隐式地说w = iota,因此w == 3。其实上面y和z可同样不用"= iota" ) const v = iota // 每遇到一个const 关键字, iota 就会重置,此时 v == 0 const ( h, i, j = iota, iota, iota //h=0,i=0,j=0 iota在同一行值相同 ) const ( a = i...
package charger import ( "errors" "time" "github.com/evcc-io/evcc/api" "github.com/evcc-io/evcc/util" "github.com/evcc-io/evcc/util/modbus" ) // EvseDIN charger implementation type EvseDIN struct { conn *modbus.Connection current int64 } const ( evseRegAmpsConfig = 1000 evseRegVehicleStatus = 1002 ) ...
package types import ( "context" "io" "net" "github.com/cyberark/secretless-broker/pkg/secretless/log" mssql "github.com/denisenkom/go-mssqldb" ) // MSSQLConnectorCtor represents the constructor of an mssqlConnector. It // exists so that its production implementation (mssql.NewConnector) can be // swapped out i...
package tracker import ( "testing" ) func TestNewTracker(t *testing.T) { id := "testid" subject := "abc123" tpl := NewPayload(pl) tr := NewTracker(tpl, id, subject) if tr.Id != id { t.Errorf("Tracker has unexpected id value: got %v want %v", tr.Id, id) } }
package list import ( "testing" "github.com/stretchr/testify/assert" ) func Test_New(t *testing.T) { // given, when list := New() // then assert.NotNil(t, list) } func Test_AddFirst_Get(t *testing.T) { assert := assert.New(t) // given list := New() list.AddFirst("피카츄") list.AddFirst("라이츄") list.AddFi...
package services // TYPE DEFINITIONS Below // BootController contains the settings that define how the remote boot will type BootController struct { AdapterName *string `json:"adapter"` // A physical adapter to bind to e.g. en0, eth0 // Servers EnableDHCP *bool `json:"enableDHCP"` // Enable Server //DHCP Configu...
package constants const CliName = "go-chain" const BlockChainName string = "go-chain"
package routers import ( "rukmini/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/status", &controllers.StatusController{}, "get:StatusCheck" ) beego.Router("/oor", &controllers.StatusController{}, "post:OutOfRotation" ) beego.Router("/b...
// Copyright 2018 xgfone // // 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 writi...
package gormgen import ( "fmt" "net/url" "path" "path/filepath" "strings" ) const gormStructsTemplate = `package {{.StructsPackage}} import ({{range .Imports}} "{{.}}"{{end}} ) {{range $tableName,$tableSchema := .DbSchema}} type {{$tableName}} struct { {{range $columnName,$columnSchema := $tableSchema}} {{$co...
package sleepsort import ( "log" "testing" ) func TestMain(t *testing.T) { v := sleepsort([]uint32{7, 3, 5, 10, 11, 20, 12, 50, 1024, 888}) log.Printf("%v", v) }
package minicon import ( "fmt" "github.com/nsf/termbox-go" // termbox ) // // Helper to make termbox a little more object oriented. // type TermBox struct { enabled bool // helper for testing draw Pen // text color clear Pen // full screen clear color terms TermChannel // non-block...
package _039_Combination_Sum import ( "testing" "github.com/stretchr/testify/assert" ) func TestCombinationSum(t *testing.T) { ast := assert.New(t) ast.Equal([][]int{{2, 2, 3}, {7}}, combinationSum([]int{2, 3, 6, 7}, 7)) ast.Equal([][]int{ []int{1, 1, 1, 1, 1, 1, 1, 1}, []int{1, 1, 1, 1, 1, 1, 2}, []int...
package utils import "strconv" func IntToHex(num int64) []byte { return []byte(strconv.FormatInt(num, 16)) }
//go:build ci // +build ci package vault import ( "os" "testing" "github.com/hashicorp/vault/api" "github.com/libopenstorage/secrets" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) type VaultTestSuite struct { suite.Suite configV1 map[string]interface{} configV2 map[string]inter...
package redis import ( "fmt" log "git.ronaksoftware.com/blip/server/internal/logger" "github.com/mediocregopher/radix/v3" "net" "sync" "time" ) /* Creation Time: 2019 - Sep - 23 Created by: (ehsan) Maintainers: 1. Ehsan N. Moosa (E2) Auditor: Ehsan N. Moosa (E2) Copyright Ronak Software G...
// Package bench_walkdir // Created by RTT. // Author: teocci@yandex.com on 2021-Aug-20 package bench_walkdir import ( "io/fs" "path/filepath" "testing" "github.com/karrick/godirwalk" ) const benchRoot = "D:/Temp/go-samples" var scratch []byte var largeDirectory string func init() { scratch = make([]byte, god...
package admin import ( "context" "encoding/json" "net/http" "time" "github.com/go-chi/chi/v5" "github.com/hi-sasaki/clean-architecture-golang-sample/pkg/registry" "github.com/hi-sasaki/clean-architecture-golang-sample/pkg/usecase/inout" ) type User struct { provider registry.Provider } func NewUser(p regist...
package pools_test import ( "context" "fmt" "github.com/exoscale/egoscale" "github.com/janoszen/exoscale-account-wiper/plugin" "github.com/janoszen/exoscale-account-wiper/pools" "github.com/janoszen/exoscale-account-wiper/terraform" "github.com/stretchr/testify/assert" "testing" ) func TestRemovingInstancePoo...
package nagiosplugin import ( "fmt" "math/rand" "testing" "time" ) func TestCheck(t *testing.T) { rand.Seed(time.Now().UTC().UnixNano()) c := NewCheck() expected := "CRITICAL: 200000 terrifying space monkeys in the engineroom | space_monkeys=200000c;10000;100000;0;4294967296" nSpaceMonkeys := float64(200000) ...
package sunet import "github.com/ilovesusu/Supreme/suinterface" type BaseRouter struct { } //处理conn之前的方法 func (b *BaseRouter) PreHandle(request suinterface.IRequest) {} //处理conn时的主方法 func (b *BaseRouter) Handle(request suinterface.IRequest) {} //处理conn之后的方法 func (b *BaseRouter) PostHandle(request suinterface.IRequ...
package umeng_sdk_push import ( "strconv" "time" ) type UnicastIOS struct { NotificationIOS } func NewUnicastIOS(textMessage string, deviceToken string, account UmengAccount) (UmengResult, error) { unicast := &UnicastIOS{ NotificationIOS{}, } unicast.setConfig(account.APP_MASTER_SECRET) payload := &Payload...
package bst import ( "fmt" ) //Common Node struct for AVL and BST type Node struct { Left *Node Right *Node Parent *Node V int H int //Height is only used for AVL } func newNode(l *Node, r *Node, p *Node, v int) *Node { return &Node{Left: l, Right: r, Parent: p, V: v, H: 1} } func Insert(root *N...
package algo_test import ( "fmt" "testing" "github.com/bpatel85/learn-go/pkg/algo" ) func TestOverlappingIntervals(t *testing.T) { input := []algo.Interval{ {Start: 1, End: 2, Group: "a"}, {Start: 3, End: 5, Group: "b"}, {Start: 2, End: 3, Group: "a"}, {Start: 6, End: 9, Group: "b"}, {Start: 8, End: 9,...
/* Copyright 2018 The Doctl 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 agreed to ...
package quips import ( "fmt" G "github.com/ionous/sashimi/game" "sort" ) // QuipSort ranks quips by the importance of their comments. type QuipSort struct { quips []quipScore } // record for tracking sorted scores type quipScore struct { quip G.IObject rank int } func (s quipScore) String() string { return f...
/* meeetup.com API */ package lag import ( "encoding/json" "fmt" "io" "net/url" "time" "appengine" "appengine/urlfetch" ) const ( apiURL = "http://api.meetup.com/2/events" key = "3f27774e3316b736c4762233f53a6f" groupName = "Los-Angeles-Gophers" ) var laLoc *time.Location type Meetup struct { UR...
package kncloudevents import ( gohttp "net/http" cloudevents "github.com/cloudevents/sdk-go/v1" "github.com/cloudevents/sdk-go/v1/cloudevents/transport/http" "go.opencensus.io/plugin/ochttp" "go.opencensus.io/plugin/ochttp/propagation/b3" "knative.dev/pkg/tracing" ) func NewDefaultClient(target ...string) (clo...
package logwrapper import ( "fmt" ) func New(servicename string) *Logger{ var log Logger if (servicename != ""){ fmt.Printf(servicename) log:= new (Logger) log.serviceName = servicename } return &log } type Logger struct { serviceName string }
package sms import ( "go.m3o.com/client" ) func NewSmsService(token string) *SmsService { return &SmsService{ client: client.NewClient(&client.Options{ Token: token, }), } } type SmsService struct { client *client.Client } // Send an SMS. func (t *SmsService) Send(request *SendRequest) (*SendResponse, er...
package problem0232 // MyQueue is a struct type MyQueue struct { queue []int } // Constructor initialize func Constructor() MyQueue { return MyQueue{} } // Push element x to the back of queue. func (this *MyQueue) Push(x int) { this.queue = append(this.queue, x) } // Pop removes the element from in front of queu...
// This file was generated by counterfeiter package fake_retainer import ( "sync" "github.com/cloudfoundry-incubator/garden-shed/layercake" "github.com/pivotal-golang/lager" ) type FakeRetainer struct { RetainStub func(log lager.Logger, id layercake.ID) retainMutex sync.RWMutex retainArgsForCall [...
package sample_data import ( "context" "encoding/json" "fmt" "github.com/gewenyu99/hardware-coverity/hardware-coverity-go/coverity" "github.com/olivere/elastic" "io/ioutil" "os" "strings" ) func LoadSample(esClient *elastic.Client) { esClient.DeleteIndex("driver").Do(context.Background()) esClient.DeleteInd...
// Copyright 2019 The gVisor 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 agree...
package bytedance import "fmt" func Code1017() { arr := []int{1, 3, 1, 1, 1} targget := 3 fmt.Println(search(arr, targget)) } /** 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 你可以假设数组中不存在重复的元素。 你的算法时间复杂度必须是 O(log n) 级别。 示例 1: 输入: nums...
package main import ( "fmt" "os" ) const ( N int = 1000 ) func main() { f, _ := os.Open("input.txt") defer f.Close() fabric := [N][N]int{} fabricclaims := [N][N]int{} claims := map[int]bool{} overlapping := map[int]bool{} var id, x, y, w, h int for { _, err := fmt.Fscanf(f, "#%d @ %d,%d: %dx%d\n", &id, ...
package main import ( "fmt" "log" "syscall" "unsafe" "github.com/elazarl/goproxy" "encoding/base64" "net/http" "strings" "os" "net/url" ) var ( modsecur32 = syscall.NewLazyDLL("secur32.dll") procAcquireCredentialsHandleW = modsecur32.NewProc("AcquireCredentialsHandleW") procFreeCredentialsHandle = ...
package main /*Golang关于类型设计的一些原则 1·变量包括 (type, value) 两部分 。所以为什么nil != nil了 2·type包括static type 和 concrete type, 前者是编码过程中的类型(如int、string), 后者是runtime系统的类型 3·类型断言是否成功,取决于concrete type, 因此一个reader变量如果它的concrete type 也实现了write方法, 就可以断言为writer @反射主要与Golang的 interface 类型相关(它的 type 是concrete type),只有interface类型才...
package main import ( extr "github.com/nci/gsky/crawl/extractor" "bufio" "encoding/json" "log" "os" ) func ensure(err error) { if err != nil { log.Fatal(err) } } func main() { if len(os.Args) != 2 { log.Fatal("Please provide a path to a file or '-' for reading from stdin") } path := os.Args[1] if p...
package br import ( "regexp" "strings" "time" "github.com/AlekSi/pointer" "github.com/olebedev/when/rules" ) func CasualDate(s rules.Strategy) rules.Rule { overwrite := s == rules.Override return &rules.F{ RegExp: regexp.MustCompile("(?i)(?:\\W|^)(agora|hoje|(?:de\\s|nesta\\s|esta\\s)noite|última(?:s|)\\s*...
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package kerberos interacts with the Kerberos system daemon. package kerberos import ( "context" "os" "github.com/godbus/dbus/v5" "github.com/golang/protobuf/proto" ...
package main import ( "encoding/json" "html/template" "log" "net/http" "path/filepath" "time" "github.com/gorilla/websocket" "github.com/jmoiron/sqlx" hash "github.com/speps/go-hashids" ) var ( hub = Hub{sessions: make(map[int]*Session)} upgrader = websocket.Upgrader{ ReadBufferSize: 1024, Write...
/* @Time : 2019/9/6 18:56 @Author : zxr @File : famous @Software: GoLand */ package define //名句--主题 type Classify struct { ThemeTitle string Title string LinkUrl string Sort int ContentList []Content } //主题下的分类信息 一个主题下有多个分类 type ThemeCategory struct { Title string LinkUrl string ...
package grpc import ( "fmt" "net" "os" "os/signal" "github.com/sirupsen/logrus" grpc "google.golang.org/grpc" ) // Server can start grpc server handling github most active contributors requests. type Server struct { service ServiceServer address string l logrus.FieldLogger } // NewServer creates new ...
package qiisync import ( "io" "io/ioutil" "os" "path/filepath" "strings" "testing" "github.com/google/go-cmp/cmp" ) func TestLoadConfiguration(t *testing.T) { tempDir, err := ioutil.TempDir("testdata", "temp") t.Cleanup(func() { if err := os.RemoveAll(tempDir); err != nil { t.Errorf("remove tempDir: %v...
package handlers import ( "encoding/json" "net/http" "path" "strconv" "strings" "time" "wayneli.me/m/servers/gateway/models/users" "wayneli.me/m/servers/gateway/sessions" ) //Creates a new HandlerContext with a signing key a sessionsStore and a usersStore func NewHandlerContext(key string, sessionsStore sess...
package model import ( "golangWeixin/common" "time" "github.com/jinzhu/gorm" ) type KeywordsReply struct { Model //ID int `gorm:"primary_key;column:id"` //Status int `gorm:"column:status"` Key string `gorm:"column:key_word"` MsgType int `gorm:"column:msg_type"` // text,image,voice, --video...
package pipelinerun import ( "bytes" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "text/template" ) type templateVariables struct { Namespace string Name string Version string Kind string Group string } func dashboardURL(pr *v1beta1.PipelineRun) string { url, ok := pr.Annotations...
// disk package node import ( "bufio" "fmt" linuxproc "github.com/c9s/goprocinfo/linux" "os" "strings" "time" ) var old_diskstat_array []linuxproc.DiskStat var new_diskstat_array []linuxproc.DiskStat var disk_last_time int64 const UINT_MAX = 4294967295 func Get_submit_float_stat_str(hostname, plugin, plugin_i...
package main import ( "fmt" "net" "net/rpc/jsonrpc" rpcdemo "practice/rpc" ) func main() { conn, err := net.Dial("tcp", "127.0.0.1:8888") if err != nil { panic(err) } client := jsonrpc.NewClient(conn) var result float64 err = client.Call("DemoService.Div", rpcdemo.Args{25, 100}, &result) if err != nil { ...
// Copyright (C) 2019 Storj Labs, Inc. // See LICENSE for copying information. package tlsopts import ( "crypto/tls" "crypto/x509" "crypto/x509/pkix" "os" "github.com/spacemonkeygo/monkit/v3" "github.com/zeebo/errs" "storj.io/common/identity" "storj.io/common/peertls" "storj.io/common/peertls/extensions" ...
package main import _ "github.com/lightbrotherV/gin-protobuf/protoc-gen-lightbrother/apidoc"
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package assets_test import ( "crypto/ed25519" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/bit...