text
stringlengths
11
4.05M
package models import ( "github.com/astaxie/beego/orm" "github.com/astaxie/beego" "fmt" "time" "math/rand" ) const ( mysqlDriver = "mysql" ) type Poetry struct { Id int64 `orm:"auto;index"` Url string Content string `orm:"type(text)"` Author string `orm:"size(128)"` Interpret string `orm...
package main import ( "fmt" "log" "net/http" "os" "github.com/sensu-community/sensu-plugin-sdk/sensu" "github.com/sensu/sensu-go/types" ) // Config represents the check plugin config. type Config struct { sensu.PluginConfig Example string } var ( plugin = Config{ PluginConfig: sensu.PluginConfig{ Name...
package gunit import ( "testing" ) func TestBatchCheck(t *testing.T) { RunTest(&BatchCheckTest{}, t) } type BatchCheckTest struct { } func (self *BatchCheckTest) TestSanity(c *Case) { c.Batch(self.foo()). AssertEquals(1). AssertEquals(-1). AssertNil() } func (self *BatchCheckTest) TestSkip(c *Case) { c.B...
package commands import ( "errors" "flag" ) type indictSetup struct { flags *flag.FlagSet } func setupForIndict() indictSetup { flags := flag.NewFlagSet("indict", flag.ExitOnError) return indictSetup{ flags: flags, } } func (setup indictSetup) Parse(args []string) Command { setup.flags.Parse(args) paths...
package trace //GinTrace .. type GinTrace struct { traceID string } //TraceID .. func (g *GinTrace) TraceID() string { return g.traceID } //NewGinTrace .. func NewGinTrace(s string) Trace { return &GinTrace{ traceID: s, } }
package Problem0556 import "sort" func nextGreaterElement(n int) int { nums := make([]int, 0, 10) lastTail := n % 10 // 用于标记 n 已经为其能表现的最大值 // 例如, n == 4321,就不可能变得更大了 isMax := true for n > 0 { tail := n % 10 if tail < lastTail { // 较高位上存在较小的值 // n 还可以变大 isMax = false } lastTail = tail nums = ...
package main import ( "fmt" "github.com/boggo/neat/experiments/threes/libthrees" "math" "math/rand" ) var D = libthrees.DOWN var U = libthrees.UP var R = libthrees.RIGHT var L = libthrees.LEFT var tMoves = []libthrees.Direction{D, U, R, L} func randMove(g libthrees.Game) (libthrees.Direction, bool) { if g.IsOve...
// Exercise 06_appendonlylog guides you through using replay as an append-only-log. Since // it is possible to directly consume RunCreated events (with their data) from // application logic via a reflex consumer, modelling an append-only-log is as simple as defining // a worklfow with only an input and without any logi...
package settings import ( "github.com/cjburchell/go-uatu" "github.com/cjburchell/tools-go/env" ) var Log = log.CreateDefaultSettings() var PubSubAddress = env.Get("PUB_SUB_ADDRESS", "tcp://localhost:4222") var PubSubToken = env.Get("PUB_SUB_TOKEN", "token") var DataServiceToken = env.Get("COMMAND_TOKEN", "token")
package slice func elimnateAdjDuplicate(s []string) []string { n := len(s) for i := 0; i < n-1; i++ { if s[i] == s[i+1] { copy(s[i:], s[i+1:]) //costy n-- } } return s[:n] } func elimnateAdjDuplicate1(s []string) []string { c := 0 for _, str := range s { if s[c] == str { continue } c++ s[c]...
package piscine func Capitalize(s string) string { sring := []rune(s) // кастинг : создаем массив рун cast len := 0 // вычисление длины строки for range sring { len++ } for i, bykva := range sring { // дайет доступ к каждой букве и диджителу if i == 0 || !isAlphaNum(sring[i-1]) { // проверяем если первая б...
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package readcloser import "io" // MultiReadCloser is a MultiReader extension that returns a ReaderCloser // that's the logical concatenation of the provided input readers. // They're read sequentially. Once all inputs have returned EOF, /...
package main import ( "github.com/gin-gonic/gin" "strconv" "encoding/json" ) const JsonByteStreamHeader = "application/json; charset=utf-8" const FloatType = "float" const StringType = "string" const BinaryType = "binary" func main(){ r := gin.Default() r.POST("/learn", GetLearningRequest) r.POST("/learnIon...
package sort import ( "fmt" "math/rand" "testing" "github.com/stretchr/testify/require" ) func TestHeap(t *testing.T) { randArray := func() []string { n := 1000 // 000 -> 999 array := make([]string, n) for i := 0; i < n; i++ { array[i] = fmt.Sprintf("%03d", i) } for i := 0; i < n; i++ { j := i +...
package controllers import ( "github.com/revel/revel" ) type App struct { *revel.Controller } func (c *App) Index() revel.Result { return c.Render() } func (c *App) GetUser(id int) revel.Result { a := 1 + id return c.RenderJSON(a) }
package aliastest import "fmt" func Get() { fmt.Println("get") } func init() { fmt.Println("init") } func main() { fmt.Println("test step 2") }
package model import ( "easyurl/infra/db/mysql" sq "github.com/Masterminds/squirrel" "log" ) type ApiDevKeyItem struct { ApiDevKey string `json:"api_dev_key"` UserId uint32 `json:"user_id"` Status uint8 `json:"status"` CreateTs uint64 `json:"create_ts"` UpdateTs uint64 `json:"update_ts"` } func GetO...
package main import ( "fmt" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/loopfz/gadgeto/tonic" "github.com/wI2L/fizz" "github.com/wI2L/fizz/openapi" ) // NewRouter returns a new router for the // Pet Store. func NewRouter() (*fizz.Fizz, error) { engine := gin.New() engine.Use(cors.De...
package main import ( "fmt" "sync" "testing" "gitgud.io/softashell/comfy-translator/translator" ) func TestQueue(t *testing.T) { q := NewQueue() req := translator.Request{ Text: "test", } if len(q.items) != 0 { t.Error("Queue not empty?") } ch, wait := q.Join(req) if ch != nil { t.Error("Returned...
/** * @author liangbo * @email liangbogopher87@gmail.com * @date 2017/10/11 22:58 */ package model import ( "time" "pet/utils" "third/gorm" ) // 用户信息表 type User struct { UserId int64 `gorm:"primary_key"; sql:"AUTO_INCREMENT"` Phone string `sql:"type:va...
package db import ( "context" "encoding/json" "fmt" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/model" "github.com/yandex-cloud/ydb-go-sdk" "github.com/yandex-cloud/ydb-go-sdk/table" ) func (r *repository) GetTODOList(ctx context.Context, id model.TODOListID) (*model.TODOList, err...
package acmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00200106 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:acmt.002.001.06 Document"` Message *AccountDetailsConfirmationV06 `xml:"AcctDtlsConf"` } func (d *Document0020...
package generator import ( "fmt" "github.com/golang/protobuf/ptypes" "github.com/goombaio/namegenerator" "github.com/yaminmhd/go-kafka-producer-protobuf/generatedProtos/person" "math/rand" "time" ) func NewPerson() *person.PersonMessage { timestamp, _ := ptypes.TimestampProto(time.Now().UTC()) person := &pers...
package circular import ( "fmt" "errors" ) type Buffer struct { capacity int nextRead, nextWrite int isFull bool buffer []byte } func NewBuffer(size int) *Buffer { buffer := make([]byte, size) return &Buffer{ capacity: size, nextRead: 0, nextWrite: 0, isFull: false, buffer: buffer, } } func (buff...
package libminio import ( "bytes" "image" "image/jpeg" _ "image/png" "log" "net/http" "os" "testing" ) func TestLibMinio(t *testing.T) { client := NewClient() client.Host = "-" client.AccessKey = "-" client.SecretKey = "-+" client.Bucket = "" client.Region = "-" client.SSL = true file, _ := os.Open("...
package pkg import ( "bytes" "encoding/json" "fmt" "os" "reflect" "regexp" "text/template" "github.com/Masterminds/sprig/v3" "github.com/goccy/go-yaml" "github.com/pkg/errors" ) func GetTPLFuncsMap() template.FuncMap { tplFuncs := make(template.FuncMap) // Add all Sprig functions for key, fn := range s...
package service import ( "context" pb "github.com/johnbellone/persona-service/internal/gen/persona/api/v1" ptypes "github.com/johnbellone/persona-service/internal/gen/persona/type" "github.com/johnbellone/persona-service/internal/server" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type Gro...
// CSV parser package main import "encoding/csv" import "io/ioutil" import "io" import "os" import "fmt" import "strings" var Debug bool const dbgLimit = 100 func ParseCsv(filename string, columnsToParse map[string]string) []Entity { file, err := os.Open(filename) if err != nil { panic(err) } if Debug { p...
package main import ( "bytes" "crypto/tls" "encoding/json" "fmt" "github.com/icza/dyno" flags "github.com/jessevdk/go-flags" "golang.org/x/net/http2" "io/ioutil" "log" "net/http" "net/url" "os" "strconv" "strings" "time" ) // https://golang.org/pkg/net/http/ // https://godoc.org/github.com/jessevdk/go-...
// hasarace.go // go run -race hasarace.go package main import "fmt" var x int func main() { for i := 1; i <= 1000; i++ { go func() { x++ }() } fmt.Println(x) }
package main import ( "fmt" "os" "path/filepath" "regexp" ) const ( jsDRegEx = `\.js(\?*.*\d*")` jsSRegEx = `\.js(\?*.*\d*')` cssDRegEx = `\.css(\?*\w*=*\d*")` cssSRegEx = `\.css(\?*\w*=*\d*')` jsDVFormat = ".js?v=%d\"" jsSVFormat = ".js?v=%d'" cssDVFormat = ".css?v=%d\"" cssSVFormat = ".css?v...
package socketmode import "encoding/json" // Event is the event sent to the consumer of Client type Event struct { Type EventType Data interface{} // Request is the json-decoded raw WebSocket message that is received via the Slack Socket Mode // WebSocket connection. Request *Request } type ErrorBadMessage str...
package main import ( "fmt" "github.com/sinksmell/files-cmp/client/utils" "github.com/sinksmell/files-cmp/models" "testing" ) var ( HOST string = "http://localhost:8080/v1/check" HASH_URL string = "/hash" FILE_URL string = "/file" ) // 测试是否能正确post json数据 func TestPostHash(t *testing.T) { req := &models....
/* * @lc app=leetcode id=144 lang=golang * * [144] Binary Tree Preorder Traversal */ // @lc code=start /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func preorderTraversal(root *TreeNode) []int { if root == nil { return n...
package base type Repository interface { NextIdentity() Identity }
package main import "errors" // User represents a collection of Users type User struct { ID string followers map[*User]bool } const ( errUnknownCommand = "Unknown message type" ) // Follow another User func (c *User) Follow(other *User) { other.followers[c] = true } // Unfollow another user func (c *Use...
package routers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/context/param" ) func init() { beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"], beego.ControllerComments{ Meth...
// Copyright 2020 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 checker import ( "context" "errors" "github.com/cybertec-postgresql/vip-manager/vipconfig" ) // ErrUnsupportedEndpointType is returned for an unsupported endpoint var ErrUnsupportedEndpointType = errors.New("given endpoint type not supported") // LeaderChecker is the interface for checking leadership typ...
package main import ( "fmt" "log" "math/rand" "os" "time" "github.com/codegangsta/cli" "gopkg.in/gin-gonic/gin.v1" ) func main() { app := cli.NewApp() app.Name = "rubusidaeus" app.Usage = "Serve image form raspberry pi camera, but quickly" app.Flags = []cli.Flag{ cli.IntFlag{ Name: "port", Valu...
package main import ( "fmt" ) func main() { var a, b, c int fmt.Scanln(&a) fmt.Scanln(&b) c= a + b fmt.Println("SOMA =",c) }
/* 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...
// Generic OneWire driver. package embd import "sync" type w1BusFactory func(byte) W1Bus type w1Driver struct { busMap map[byte]W1Bus busMapLock sync.Mutex ibf w1BusFactory } // NewW1Driver returns a W1Driver interface which allows control // over the OneWire subsystem. func NewW1Driver(ibf w1BusFactory) W...
package dao type CreatePoll struct { Question string Options []string } type OptionIdUserId struct { OptionId int ` binding:"required"` UserId int ` binding:"required"` } type QuestionIdUserId struct { QuestionId int ` binding:"required"` UserId int ` binding:"required"` }
// Package usecase defines the business logic of the requirement. // The general flow of the requirements are explicitly stated in the code. package usecase
package server import ( "net/http" "github.com/google/uuid" ) // RequestID retrieves the request id from the context. func RequestID(req *http.Request) uuid.UUID { requestID, ok := req.Context().Value(requestIDKey).(uuid.UUID) if !ok { return uuid.Nil } return requestID }
package transpose func Transpose(input []string) []string { if len(input) == 0 { return []string{} } totalNumberOfRows := maxRows(input) totalNumberOfColumns := len(input) output := make([]string, totalNumberOfRows[0]) for column := 0; column < totalNumberOfColumns; column++ { for row := 0; row < totalNumbe...
package mt type AnimType uint8 const ( NoAnim AnimType = iota // none VerticalFrameAnim // vertical frame SpriteSheetAnim // sprite sheet maxAnim ) //go:generate stringer -linecomment -type AnimType type TileAnim struct { Type AnimType //mt:assert %s.Type < maxAnim...
package generator import ( "fmt" "github.com/jazztong/csla/cross" "github.com/jazztong/csla/provider/fileloader" "io/ioutil" "os" "path" ) type awsAPILambdaGolang struct { TemplatePrefix string } func (t *awsAPILambdaGolang) Generate(req Request) { // Create folder if err := os.Mkdir(req.Name, os.ModePerm);...
package routes import ( "devbook-api/src/controllers" "net/http" ) var authRoute = Route{ URI: "/login", Method: http.MethodPost, Handler: controllers.Auth, RequestAuth: false, }
package transport // AdminSignIn 用户登录参数映射 type AdminSignIn struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } // AdminCreate 创建后台用户映射 type AdminCreate struct { Username string `form:"username" json:"username" bindi...
package core import ( "io" "os" "path" "github.com/evan-buss/openbooks/dcc" "github.com/evan-buss/openbooks/util" ) func DownloadExtractDCCString(baseDir, dccStr string, progress io.Writer) (string, error) { // Download the file and wait until it is completed download, err := dcc.ParseString(dccStr) if err !...
package models_test import ( "github.com/APTrust/exchange/constants" "github.com/APTrust/exchange/models" "github.com/stretchr/testify/assert" "os" "testing" "time" ) var bagDate time.Time = time.Date(2104, 7, 2, 12, 0, 0, 0, time.UTC) var ingestDate time.Time = time.Date(2014, 9, 10, 12, 0, 0, 0, time.UTC) fu...
/* Copyright (c) 2018 VMware, Inc. 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 t...
// Package pubsub contains utilities for handling Google Cloud Pub/Sub events. package pubsub import ( "fmt" "regexp" "strings" "time" "cloud.google.com/go/functions/metadata" "github.com/GoogleCloudPlatform/functions-framework-go/internal/fftypes" ) const ( pubsubEventType = "google.pubsub.topic.publish" ...
package dic import ( "fmt" "bytes" "encoding/gob" "github.com/soundTricker/kagome/data" ) type Content struct { Pos, Pos1, Pos2, Pos3, Katuyougata, Katuyoukei, Kihonkei, Yomi, Pronunciation string } func (this Content) String() string { return fmt.Sprintf("%v, %v, %v, %v, %v, %v, %v, %...
package perf import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "strings" "github.com/gofrs/uuid" "github.com/manifoldco/promptui" termbox "github.com/nsf/termbox-go" log "github.com/sirupsen/logrus" "github.com/layer5io/meshery/internal/sql" "github.com/ghodss/yaml" "github.com/layer5io/m...
/* No one is quite certain what the emoticon >:U is intended to represent, but many scholars believe it looks like an angry duck. Let's assume that's the case. Task Given an integer n between 0 and 3 inclusive, print or return quack if n = 0, >:U if n = 1, U U > : U U > U U > : U U UUU if n...
package gobchest import ( "fmt" "math/rand" "time" ) var ( pt = fmt.Printf ) func init() { rand.Seed(time.Now().UnixNano()) }
package response import ( //"encoding/json" ) func SuccRes() map[string]interface{} { return map[string]interface{} { "ok": true, } } func FailRes(message interface {}) map[string]interface{} { return map[string]interface{} { "ok": false, "message": message, } }
package container import ( "bitbucket.org/avanz/anotherPomodoro/common" "bitbucket.org/avanz/anotherPomodoro/custom/widget" "bitbucket.org/avanz/anotherPomodoro/repository" "encoding/json" "fmt" "fyne.io/fyne" "fyne.io/fyne/theme" "time" ) type PomodoroDoneContainer struct { *fyne.Container repository repos...
package app import ( "errors" "github.com/BurntSushi/toml" "github.com/domac/ats_check/util" "path/filepath" ) type AppConfig struct { Parents []string Haproxys []string Parents_config_path string Remap_config_path string Records_config_path string Health_ch...
package foundation import ( "fmt" "html/template" "io/ioutil" "os" "path/filepath" "strings" ) type ( _Template struct { Filters []Filter Delims Delimiters } Delimiters struct { Left, Right string } ) var ( Template _Template = _Template{ // Sets default html template filters Filters: []Filter...
package main import ( "bufio" "fmt" "github.com/pkg/errors" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing" "gopkg.in/src-d/go-git.v4/plumbing/filemode" "gopkg.in/src-d/go-git.v4/plumbing/object" "io" "log" "os" "path" "strings" "unicode" ) func main() { if len(os.Args) != 2 { log.Fatal...
package gotoml import ( "fmt" ) const ( // parse erros CouldNotParse = iota // get errors KeyNotFound InvalidType ) type ParseError struct { Reason int LineNumber int } type GetError struct { Reason int RequestedKey string RequestedType string ActualValue string } func (e *GetError) Erro...
package main_test import ( analysis "github.com/plholx/awesome-go-analysis" "testing" ) func TestInitDB(t *testing.T){ analysis.InitDB() }
package main import ( "fmt" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type GeneralRecord struct { Type string `bson:"type"` } type Person struct { Name string `bson:"name"` Phone string `bson:"phone"` } type Company struct { Name string `bson:"company"` Boss string `bson:"boss"` } func main() { ses...
package cmd import ( "github.com/myechuri/ukd/server/api" "github.com/spf13/cobra" "golang.org/x/net/context" "google.golang.org/grpc" "log" ) var ( ukName string imageLocation string serverAddress string visor string ) func start(cmd *cobra.Command, args []string) { // TODO: TLS serverAddr...
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { reader := bufio.NewReaderSize(os.Stdin, 100001) line, _, _ := reader.ReadLine() t, _ := strconv.Atoi(string(line)) for ; t > 0; t-- { text, _, _ := reader.ReadLine() cnt := 0 for i := 0; i < len(text)-1; i++ { if text[i] == text[i+1]...
package local import ( "fmt" "os" "os/exec" "path/filepath" "runtime" "time" "github.com/fatih/color" "github.com/linuxkit/rtf/logger" "github.com/linuxkit/rtf/sysinfo" ) const ( // GroupFileName is the name of the group script (without the extension) GroupFileName = "group" // PreTestFileName is the nam...
package Parse import ( "../Misc" "bufio" "errors" "os" ) //Parsing -p and -P supplied parameters func ParsePass(h *Misc.HostInfo) ([]string, error) { switch { case h.Passfile != "" && h.Password != "": return nil, errors.New("-p and -P cannot exist at the same time") case h.Passfile == "" && h.Password == ""...
// 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...
// Copyright (c) 2020 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package starlark import ( "fmt" "os" "path/filepath" "strings" "testing" "go.starlark.net/starlark" "go.starlark.net/starlarkstruct" ) func TestKubeCapture(t *testing.T) { tests := []struct { name string kwa...
package main import ( "fmt" "math/rand" "time" ) func generateRandomNrBetween(low int, high int) int { return rand.Intn(high-low) + low + 1 } func guessNumberBetweenNumbers(number int, low int, high int) { var tries = 0 rand.Seed(time.Now().UnixNano()) for { tries++ fmt.Printf("\nTry %1v - ", tries) fmt...
package lintcode /** * @param n: An integer * @param nums: An array * @return: the Kth largest element */ func kthLargestElement(n int, nums []int) int { quickSort(nums) return nums[len(nums)-n] } func quickSort(nums []int) { if len(nums) == 0 || len(nums) == 1 { return } i := 0 j := len(...
package templates import ( "context" "github.com/profzone/eden-framework/pkg/courier" "github.com/profzone/eden-framework/pkg/courier/httpx" ) func init() { Router.Register(courier.NewRouter(CreateTemplate{})) } // 创建模板 type CreateTemplate struct { httpx.MethodPost } func (req CreateTemplate) Path() string { ...
package game_map import ( "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/combat" "github.com/steelx/go-rpg-cgm/gui" "github.com/steelx/go-rpg-cgm/world" ) type CombatTargetState struct { CombatState *CombatState Stack *gui.StateStack ...
package postgres // schema name const prefix = `montesquieu` // This stmt is run on every startup to ensure that database structures exist, and if they don't, it creates them const stmtStartup = ` create schema ` + prefix + ` create table if not exists users ( id bigserial not null ...
package main import ( "fmt" // "html" "log" "net/http" "github.com/gorilla/mux" "database/sql" _ "github.com/go-sql-driver/mysql" "encoding/json" "strconv" ) type Todo struct { ID int `json:"id"` Value string `json:"value"` Checked bool `json:"checked"` } // handle all the different API routes func main...
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // LineFromFloat64Array3 returns a driver.Valuer that produces a PostgreSQL line from the given Go [3]float64. func LineFromFloat64Array3(val [3]float64) driver.Valuer { return lineFromFloat64Array3{val: val} } // LineToFloat64Array3 returns...
package libStarter import "io" type IFormatter interface { Format(cmdParams *CmdParams) IFormatter WriteOut(writer io.Writer) error } // 格式化信息结构体 type FormatterStruct struct { PackageName string ImportList map[string]ImportItem Name string StructName string TypeName string } type ImportItem struc...
package server import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/gorilla/mux" "github.com/holly-graham/scheduleapi/schedule" ) type ScheduleServer struct { scheduleService *schedule.ScheduleService } func NewServer(scheduleService *schedule.ScheduleService) *ScheduleServer { return &Schedule...
package main import ( "fmt" //"net/http" //"os" //"path" //"strings" //"encoding/json" "github.com/espebra/filebin2/dbl" "github.com/espebra/filebin2/s3" "time" ) type Lurker struct { dao *dbl.DAO s3 *s3.S3AO interval time.Duration retention uint64 } func (l *Lurker) Init(interval int, ret...
package datapool import ( "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "math" "math/rand" "net/http" "os" "strconv" "sync" "time" //_ driver for tds "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" _ "github.com/thda/tds" ) var ( //...
package auth import ( "context" "fmt" "log" "os" "strings" "cloud.google.com/go/firestore" "cloud.google.com/go/functions/metadata" firebase "firebase.google.com/go" usermodel "github.com/modeckrus/firebase/usermodel" ) //AuthEvent is type AuthEvent struct { Email string `json:"email"` UID string `json:...
package main import ( "strconv" "sync" "github.com/prometheus/client_golang/prometheus" ) const prefix = "ping_" var ( labelNames = []string{"target", "ip", "ip_version"} bestDesc = prometheus.NewDesc(prefix+"rtt_best_ms", "Best round trip time in millis", labelNames, nil) worstDesc = prometheus.NewDesc(pr...
package sessions import ( "backend/internal/domain" "github.com/gorilla/sessions" ) type gorillaSession struct { session *sessions.Session } func NewGorillaSession(session *sessions.Session) Session { return &gorillaSession{ session: session, } } func (g *gorillaSession) IsAuthenticated() bool { ok, value :...
package main import ( "fmt" "io/ioutil" "math/rand" "time" ) func random(min, max int) int { return rand.Intn(max-min) + min } func main() { // http://golangcookbook.blogspot.ca/2012/11/generate-random-number-in-given-range.html rand.Seed(time.Now().Unix()) byteArray, err := ioutil.ReadFile("./tests/pdfs/p...
package wolfenstein import ( "github.com/llgcode/draw2d/draw2dimg" "github.com/llgcode/draw2d/draw2dkit" "image/color" "math" ) type GameState struct { level []int mapSize int blockSize int player Player } type Player struct { position Point delta Point } type Point struct { x float64 y ...
package router import ( "errors" "github.com/nedp/command" ) type Slots interface { // Add finds a free slot and assigns it to the specified command. // // Returns // the index of the slot assigned to the command. Add(c command.Interface) (int, error) // Run is a wrapper for Run on the command in slot i. /...
package models import ( _ "github.com/lib/pq" "github.com/astaxie/beego/orm" "time" "fmt" "github.com/astaxie/beego" "github.com/Pallinder/go-randomdata" ) type AuthUser struct { Id int First string Last string Email string Password string Reg_key string Reg_date time....
package main func longestWord(words []string) string { isLiving := make(map[string]bool) for i := 0; i < len(words); i++ { isLiving[words[i]] = true } return longestWordExec(isLiving, "") } func longestWordExec(isLiving map[string]bool, nowStr string) string { ans := nowStr for i := 'a'; i <= 'z'; i++ { str...
/* For license and copyright information please see LEGAL file in repository */ package approuter import ( "fmt" "os" "os/signal" "syscall" "time" ) // Server represents an ChaparKhane server needed data to serving as server. type Server struct { Status int // 0:stop 1:running Gracef...
package main import ( "fmt" "os" ) var moofUrl string = "C:/Users/peili/Desktop/26f_init.mp4" func main() { fmt.Println("hu test begin") fileOP, err := os.Open(moofUrl) if err != nil { println("failed to open source file.") return } defer fileOP.Close() fileStat, _ := fileOP.Stat() fmt.Println("xxxxx f...
package csv import ( "encoding/csv" "io" ) func ReadFile(r io.Reader) ([]string, error) { csvReader := csv.NewReader(r) macAddresses := make([]string, 0) for { record, err := csvReader.Read() if err == io.EOF { break } if err != nil { return nil, err } macAddresses = append(macAddresses, reco...
package cmd import ( "fmt" "github.com/alewgbl/fdwctl/internal/config" "github.com/alewgbl/fdwctl/internal/database" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/model" "github.com/alewgbl/fdwctl/internal/util" "github.com/spf13/cobra" "strconv" "strings" ) var ( createCmd...
package image import ( "bytes" "context" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pkg/errors" "io" "io/ioutil" "strings" ) type FakeDownloader struct { DownloadContents []byte DownloadError error } func (fd FakeDownloader) Download(url string, ctx context.Context) (io.Reader, er...
package acoustid import ( "io/ioutil" "net/http" "testing" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" hc "github.com/ocramh/fingerprinter/internal/httpclient" fp "github.com/ocramh/fingerprinter/pkg/fingerprint" ) func TestLookupFingerprintOK(t *testing.T) { httpmock.Activate() defe...
package test_helper import ( "github.com/lyokato/goidc/flow" "github.com/lyokato/goidc/prompt" ) type ( TestClient struct { id string ownerId int64 secret string redirectURI string idTokenAlg string idTokenKeyId string idTokenKey interface{} grantTypes map[string]bool ...
package domain import ( "strconv" "time" "github.com/pkg/errors" ) // Trading defines the Trading domain type Trading struct { ID int Pair string Share float64 Price float64 CreatedAt time.Time } // NewTrading builds a new Trading structure ensuring its values func NewTrading(tradeID int...