text
stringlengths
11
4.05M
package gologger import ( "fmt" "strings" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) const ( FATAL = "fatal" ERROR = "error" WARNING = "warning" INFO = "info" DEBUG = "debug" ) var levelMap = map[string]zapcore.Level{ FATAL: zapcore.FatalLevel, ERROR: zapcore.ErrorLevel, WARNING: zapcore...
package backends import ( "database/sql" "log" "time" ) const ( AuthorizationExpiration = 900 AccessExpiration = 86400 ) // 清理过期的数据 func Cleanup() error { now := time.Now() return withDbQuery(func(db dber) (err error) { var ( r1, r2, r3 sql.Result c1, c2, c3 int64 ) r1, err = db.Exec("DELET...
package business import ( "github.com/police-police-mashed-potatoes/data" "github.com/stretchr/testify/require" "strings" "testing" ) func TestSanitizeEntries_WithDateTimeNewLines_RemovesNewLines(t *testing.T) { entries := []data.Entry{ {Id: 1, DateTime: "2018-01-01\n"}, } result := SanitizeEntries(entries)...
package builder import ( "go/ast" "go/token" "math/rand" "time" "github.com/Illyrix/tidb-go-fuzz/dep/types" ) type Visitor struct { // blockIds []types.BlockIdType // current block id stack // blocks []*types.Block // all blocks in this file (unordered) // the outer block is 0x0000 parentBlockId typ...
package model // AuthdDevice a struct to rep Authrnticated Device type AuthdDevice struct { BaseModel UserID string `json:"user_id" gorm:"not null;type:varchar(20)"` IP string `json:"ip" gorm:"type:varchar(50)"` Browser string `json:"browser" gorm:"type:varchar(100)"` BrowserVersion str...
package main import ( "fmt" "time" ) func main() { ch := make(chan struct{}, 2) t := time.NewTimer(time.Second * 1) go worker(ch) //var ch2 chan struct{} for { select { case <-ch: fmt.Println("读取到了哟") case <-t.C: ch = nil } } } func worker(ch chan struct{}) { ch <- struct{}{} } //1.向nil cha...
package types // Matrix - matrix interface type Matrix interface { Shape() (rows, cols int) Rows() (rows int) Cols() (cols int) Get(row, col int) (elem int) Set(row, col, elem int) Matrix Out() }
package validate // Copyright (c) Microsoft Corporation. // Licensed under the Apache License 2.0. import ( "testing" ) func TestRxOpenShiftVersion(t *testing.T) { for _, tt := range []struct { value string want bool }{ { value: "4.3.0", want: true, }, { value: "4.3.1", want: true, }, ...
package main import "fmt" func main() { pointer() CreatePointer() } func pointer() { x := 10 fmt.Printf("value is %d\n", x) // &x การเข้าถึงที่อยู่ของ x // ผลลัพธ์ c000014078 คือเลขฐาน 2 ที่เก็บข้อมูลชุดนี้ fmt.Printf("Address x variable %x\n", &x) } // สร้าง Pointer func CreatePointer() { x := 10 // p จั...
package router import ( "net/http" ) type router struct { handlers map[string]map[string]http.HandleFunc }
package validation import ( "testing" "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors" logrusTest "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/util/validation/field" "github.com/openshift/installer/pkg/types/openstack" ) const ( validZ...
package rds import ( "fmt" "gopkg.in/redis.v4" "joebot/tools" ) var ( RC *redis.Client ) // Connect to default port func RedisInit() { RC = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) fmt.Println("Redis Ping Pong test. ...
//使用hash表从数组中找出满足a+b = c+d的两个数对 package main import "fmt" type Pairs struct { first int second int } func FindPairs(arr []int) bool { sumPair := map[int]*Pairs{} n := len(arr) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { sum := arr[i] + arr[j] if _, ok := sumPair[sum]; !ok { sumPair[sum] =...
package main import ( "bufio" "fmt" "os" "strings" ) func main() { ch1 := make(chan byte) ch2 := make(chan byte) isPalindrome := true reader := bufio.NewReader(os.Stdin) fmt.Println("Enter palindrome to check:") input, err := reader.ReadString('\n') if err != nil { fmt.Println(err) } input = strings.Repl...
package main import "fmt" func main() { var arr [3]int arr[0] = 12 arr[1] = 10 arr[2] = 16 fmt.Printf("数组首个元素的地址是:%p\n", &arr[0]) //数组本身元素的地址是上一个元素地址加上本身元素占用的字节数,例如int占8个字节,如果&arr[0]的地址是0xc00000e360,那么&arr[1]就是0xc00000e368 fmt.Printf("数组第二个元素的地址是:%p\n", &arr[1]) fmt.Printf("数组第三个元素的地址是:%p\n", &arr[2]) }
package file import ( "encoding/json" "fmt" "os" ) func load(fname string) (status, error) { if err := initIfNotExist(fname); err != nil { return status{}, fmt.Errorf("failed to init file: %w", err) } src, err := os.OpenFile(fname, os.O_RDONLY|os.O_CREATE, 0644) if err != nil { return status{}, fmt.Errorf...
package main import ( "encoding/json" "encoding/xml" "flag" "fmt" "log" "net" "os" "github.com/jrozner/sonar" ) func main() { var ( wordlist string brute bool threads int zt bool output string format string ) flag.Usage = printUsage flag.StringVar(&wordlist, "wordlist", "", "s...
package inmemory import ( "testing" "github.com/Tanibox/tania-core/src/assets/storage" "github.com/Tanibox/tania-core/src/assets/domain" "github.com/stretchr/testify/assert" ) func TestFarmEventInMemorySave(t *testing.T) { // Given done := make(chan bool) farmEventStorage := storage.CreateFarmEventStorage()...
package main //region Usings import "github.com/ravendb/ravendb-go-client" //endregion var globalDocumentStore *ravendb.DocumentStore func main() { createDocumentStore() createDatabase() createRelatedDocuments("someProductName","someSupplierName","somePhoneNumber") globalDocumentStore.Close() } func...
package problem0230 //TreeNode 树节点 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func kthSmallest(root *TreeNode, k int) int { num := 0 stack := []*TreeNode{} cur := root for num < k { for cur != nil { stack = append(stack, cur) cur = cur.Left } node := stack[len(stack)-1] if...
// Copyright 2019 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 ( "github.com/vsabreu/go-echo-tests/routes" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) const ( serverPort = ":8111" empty = "" ) func main() { e := echo.New() configureEcho(e) registerMiddlewares(e) configureStatic(e) registerRoutes(e) e.Logger.Fatal(e.S...
package main import ( "github.com/julienschmidt/httprouter" "net/http" ) // Workspace/Go/src/video_server // Workspace/Go/bin type middleWareHandler struct { router *httprouter.Router } func (handler middleWareHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { //check session vali...
package main import ( "bytes" "encoding/binary" "fmt" "testing" ) func TestBinaryCoding(t *testing.T) { data := []byte("hello") bf := bytes.NewBuffer(nil) binary.Write(bf, binary.BigEndian, data) size := binary.Size(data) o := make([]byte, size) binary.Read(bf, binary.BigEndian, o) fmt.Printf("这是原始数据:%s\n"...
package day3 import ( "strings" "testing" ) func Test_numTreesFound(t *testing.T) { testInput := "..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#" var testArray [][]string for _, line := range strings.Split(testInput, ...
package resources // Partial structure of JSON when hitting the /v2/apps endpoint type V2AppsJSON struct { NextURL string `json:"next_url"` Apps []V2App `json:"resources"` } type V2App struct { Metadata struct { GUID string `json:"guid"` } `json:"metadata"` Entity struct { Name string `json:"name"` ...
package main import "fmt" func main() { for { fmt.Println("before") break fmt.Println("after") } fmt.Println("next statemant") }
package alfred import ( "encoding/xml" "log" ) // XMLHeader is definition for XML format. const XMLHeader = `<?xml version="1.0"?>` // Item contains value list item. type Item struct { UID string `xml:"uid,attr,omitempty"` Arg string `xml:"arg,attr,omitempty"` Valid bool `...
// +build ignore package main import ( "encoding/xml" "fmt" "io" "log" "os" "runtime" "strings" ) type location struct { Data string `xml:",chardata"` } func main() { f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer f.Close() PrintMemUsage() d := xml.NewDecoder(f) count := 0 f...
package api import ( "fmt" "net/http" "net/url" "time" "github.com/cli/cli/v2/internal/ghrepo" "github.com/shurcooL/githubv4" ) type PullRequestAndTotalCount struct { TotalCount int PullRequests []PullRequest SearchCapped bool } type PullRequest struct { ID string Number i...
package models type Location struct { ID int `json:"id"` Name string `json:"name"` }
package main import ( "fmt" "log" "net/http" "github.com/microsoft/azure-databricks-operator/mockapi/router" ) func main() { router := router.NewRouter() port := ":8085" fmt.Printf("API running on http://localhost%s\n", port) log.Fatal(http.ListenAndServe(port, router)) }
/* 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 writ...
package go_leda import ( "fmt" ) type ItemType int type List struct { item ItemType next *List } func SearchList(l *List, x ItemType) *List { if l == nil { return nil } if l.item == x { return l } else { return (SearchList(l.next, x)) } } func InsertList(l *...
package gstypes import ( "context" "go/types" "rloop/Go-Ground-Station/proto" "sync" ) type Param struct { Name string Type types.BasicKind Units string Size int BeginLoop bool EndLoop bool } type NodeInfo struct { Name string ParameterPrefix string Node string...
package aoc2020 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_instruction(t *testing.T) { assert := assert.New(t) instrs, err := generateInstructionList(day08sampleInput) assert.NoError(err) assert.Equal([]instruction{ {"nop", +0}, {"acc", +1},...
package mioqq import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "net/url" "sync" "time" ) // API is the cqhttp api sdk type API struct { API string Token string client *http.Client wsPool *sync.Pool } var ( // Timeout set the mio message handler time Timeout int = 10 ) // ...
/** * @program: Go * * @description: * * @author: Mr.chen * * @create: 2020-03-06 09:30 **/ package repositories import ( "database/sql" "iris_demo/common" "iris_demo/datamodels" "strconv" ) //第一步,先开发对应的接口 //第二步,实现定义的接口 type IOrderRepository interface { //连接数据 Conn()(error) Insert(*datamodels.Order)(int64,erro...
package multiplication import ( "../matrix" "../types" ) // Matrix - matrix interface type Matrix interface { types.Matrix } // Multiply - standart func Multiply(a, b Matrix) (res Matrix) { rows := a.Rows() columns := b.Cols() res = matrix.Zeros(rows, columns) for i := 0; i < rows; i++ { for j := 0; j < c...
package server import "github.com/gin-gonic/gin" func SetRouter(r *gin.Engine) { game := r.Group("/game") game.GET("/:id/detail", GetDetailInfo) game.GET("/:id/summary", GetSummaryInfo) game.GET("/", GetSummaryOverPage) }
package test import ( "fmt" "testing" ) /** * @desc TODO * @author Ipencil * @create 2019/3/18 */ func filter(t *testing.T) { //t.SkipNow() t.Run("band_json", filterPrint) t.Run("band_cook", cook) } //json客户端发送数据 func filterPrint(t *testing.T) { t.SkipNow() /*get 请求*/ url := "http://localhost:8000/fil...
package qpx // generated by JSON-to-go type Response struct { Kind string `json:"kind"` Trips struct { Kind string `json:"kind"` RequestId string `json:"requestId"` Data struct { Kind string `json:"kind"` Airport []struct { Kind string `json:"kind"` Code string `json:"code"` Cit...
package main import ( "fmt" "github.com/boltdb/bolt" "github.com/labstack/gommon/log" "publicChain/BLC" ) func main() { cli := BLC.Cli{} cli.Run() } func boltTest() { db, err := bolt.Open("my.db", 06000, nil) if err != nil { log.Panic(err) } defer db.Close() //创建表 . err = db.Update(func(tx *bolt.Tx) ...
// Copyright 2020 Ant Group. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package tool import ( "io" "os" "os/exec" ) type BuilderOption struct { BootstrapPath string DebugOutputPath string } type Builder struct { binaryPath string stdout io.Writer stderr io.Writer } func NewBui...
package command import ( "github.com/conjurinc/summon/secretsyml" . "github.com/smartystreets/goconvey/convey" _ "golang.org/x/net/context" "io/ioutil" "os" "path" "strings" "testing" ) func TestRunAction(t *testing.T) { Convey("Using a dummy provider that returns 'mysecret'", t, func() { providerPath := p...
package frechet type PolyhedralFrechetDistance struct { AbstractFretchetDistance distfunc PolyhedralDistanceFunction } func NewPolyhedralFretchetDistance(disfunc PolyhedralDistanceFunction) PolyhedralFrechetDistance { x := PolyhedralFrechetDistance{distfunc:disfunc} x.FrechetDistance = x return x } func (this...
package main import "fmt" func main() { fmt.Println("Kyle say Hello World!") }
package brands import ( "fmt" "github.com/MrWebUzb/facade/abstract_factory/factory" ) // GetSportsFactory ... func GetSportsFactory(brand string) (factory.ISportsFactory, error) { if brand == "adidas" { return &Adidas{}, nil } if brand == "nike" { return &Nike{}, nil } return nil, fmt.Errorf("unknown br...
package ctl import ( "vchatdemo/unit/intf" ) type GoodByeImpl struct { } func (r *GoodByeImpl) Exec(in *intf.GoodByeRequest) (string, error) { s := in.S return s + " byte bye.....", nil }
package model import ( "database/sql/driver" "fmt" "io" "strconv" "time" "github.com/google/uuid" "github.com/jinzhu/gorm" validation "github.com/go-ozzo/ozzo-validation/v3" "github.com/go-ozzo/ozzo-validation/v3/is" ) type UserStatus string const ( UserStatusPending UserStatus = "PENDING" UserStatusA...
// Copyright 2020-2021 Buf Technologies, 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...
package bydefine //伟志通用modbus寄存器. const( REG_WGT=0 //重量寄存器. REG_STATE=2 //重量状态. REG_DOT=3 //小数点点位 REG_DIV_HIGH=8 REG_CALIB=20 REG_FULL_SPAN=26 REG_ADDR=30 REG_4B_CORN_K=36 //40037/40038 传感器1号角差系数(1000代表1.000) REG_2B_AUTO_CORN=44 //自动角差控制:0:启动标定;1:标定传感器1;2:标定传感器2;3:标定传感器3;4:标定传感器4;5:结束标定 REG_2B_SENSOR_NUM=4...
package util import ( "compress/gzip" "net/http" "strings" ) //CloseableResponseWriter : Custom gzip type CloseableResponseWriter interface { http.ResponseWriter Close() } type gzipResponseWriter struct { http.ResponseWriter *gzip.Writer } //Write : Custom gzip func (gzipRespWtr gzipResponseWriter) Write(dat...
/* Copyright 2014 The Kubernetes 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, ...
//go:generate protoc --gogofast_out=import_path=golang.docker.com/go-docker/api/types/plugins/logdriver:. entry.proto package logdriver
package shipping_details import ( shippingDetails "Pinjem/businesses/shipping_details" "time" "gorm.io/gorm" ) type ShippingDetails struct { ID uint `gorm:"primary_key"` OrderId uint `gorm:"not null"` DestProvinsi string `gorm:"not null"` DestKota string `gorm:"not null"` DestK...
package main import ( "fmt" "sub/app" "sub/app/helpers/confighelper" "sub/app/helpers/dbhelper" "sub/app/helpers/loghelper" "sub/app/models" "sub/app/utils" "github.com/streadway/amqp" ) // init global things... func init() { var err error // to set application configs from appConfig.yaml file err = set...
package controllers import ( "coludRenderDiscovery/discovery" "coludRenderDiscovery/models" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "time" ) type MachineController struct { beego.Controller } func (c *MachineController) Prepare() { c.Data["PROTOCOL_TYPE_REG_RENDER"] = discovery.PROTOCOL_TYPE...
package redcap type RedcapEvent struct { Event_Name string Arm_num string Day_offset string Offset_max string Offset_min string Unique_event_name string }
/* Copyright 2019 The Tekton 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...
package main import ( "time" "math" "runtime" ) type Circuit struct { In int Out int Cluster []*Neuron Results []Percept MaxConn int Inhibitors int } type Percept struct { outcome int } type RankedResult struct { outcome int amplitude int confidence float64 } fun...
package local import ( "io/ioutil" "path/filepath" "testing" u "github.com/10gen/realm-cli/internal/utils/test" "github.com/10gen/realm-cli/internal/utils/test/assert" ) func TestWriteFunctionsV1(t *testing.T) { tmpDir, cleanupTmpDir, err := u.NewTempDir("") assert.Nil(t, err) defer cleanupTmpDir() t.Run("...
package models type Post struct { ID int `json:"id"` Parent int `json:"parent"` Author string `json:"author"` Message string `json:"message"` IsEdited bool `json:"isEdited"` Forum string `json:"forum"` Thread int `json:"thread"` Created string `json:"created"` }
// Package classification of Plant API // // Documentation for Plant API // // Schemes: http // BasePath: / // Version: 1.0.0 // // Consumes: // - application/json // // Produces: // - application/json // swagger:meta package handlers import ( "log" "net/http" "strconv" "github.com/gorilla/mux" "github.com/sarav...
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "context" "time" "strconv" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/nzlov/gorm" argo "github.com/zyxar/argo/rpc" ) const ( help = `Aria2 命令:\n【/bind】:绑定Aria2\n【/unbind】:取消绑定\n【/down】:下载连接\n【/status】:查看状态` bind...
package main import ( "go/scanner" "go/token" "io/ioutil" "os" ) type Lexeme struct { pos token.Position p token.Pos tok token.Token lit string } // LexemeChan streams a source file func LexemeChan(srcpath string) (<-chan *Lexeme, error) { fs := token.NewFileSet() st, err := os.Stat(srcpath) if err != n...
// Copyright © 2020 Attestant Limited. // 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 easy import ( "fmt" "strings" "testing" ) func Test121(t *testing.T) { var a []int a = append(a, 7,1,5,3,6,4) b := maxProfit(a) fmt.Println(b) } func maxProfit(prices []int) int { l := len(prices) if l==0{ return 0 } var a [][]int for i:=0;i<l;i++ { if i == 0 { var tmp []int tmp = appen...
// for. package main import "fmt" func main() { line := "name arg1 arg2" for i := range line { fmt.Printf("%d %q %q\n", i, string(line[i]), line[i+1:]) } // not panic fmt.Printf("\nline[len(line):]\n") fmt.Printf("not panic, %%q=%q\n", line[len(line):]) }
/* Description A racing bicycle is driven by a chain connecting two sprockets. Sprockets are grouped into two clusters: the front cluster (typically consisting of 2 or 3 sprockets) and the rear cluster (typically consisting of between 5 and 10 sprockets). At any time the chain connects one of the front sprockets to o...
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "...
package main import ( "fmt" "log" "github.com/nurikevenoglu/reddit" ) func main(){ items, err := reddit.Get("golang") if err != nil { log.Fatal(err) } for i,item := range items { fmt.Println(i, item) } }
package main import ( "errors" "fmt" "io/ioutil" "log" "net/url" "os" "reflect" "strings" "time" "github.com/gdamore/tcell" "github.com/rivo/tview" yaml "gopkg.in/yaml.v2" k8s "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-g...
package libs import ( "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" accessControlContract "../contracts/accessContract" balanceContract "../contracts/balanceContract" dataCon...
// package watcher watches files in a directory recursively. // // It's meant to be used as a building block for tools that // watch files. package watcher import ( "fmt" "log" "os" "path/filepath" "strings" "github.com/go-fsnotify/fsnotify" ) // Op describes a set of file operations. Wraps fsnotify. type Op u...
/* * @Description: In User Settings Edit * @Author: your name * @Date: 2019-08-17 15:52:08 * @LastEditTime: 2019-08-24 09:40:48 * @LastEditors: Please set LastEditors */ package main import ( "encoding/json" "net/http" "strconv" "github.com/yuwe1/shuxiang/common/dber" ) //修改图书信息 func (h *BookHub) ModifyLoc...
package handler import ( "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/gorilla/mux" "github.com/stretchr/testify/require" "2019_2_IBAT/pkg/app/auth/session" mock_auth ...
package topsearch import ( "encoding/csv" "strconv" ) // Import returns a pair of index-mapped slices from the given io.Reader func Import(r *csv.Reader) ([]string, []DataSet) { names := make([]string, 0) values := make([]DataSet, 0) for { record, err := r.Read() if err != nil { break } names = app...
package main import ( "io" "log" "net" "net/http" "time" ) type ProxyHTTPSServer struct{} func (p *ProxyHTTPSServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Printf("Received request: %s %s %s\n", r.Method, r.Host, r.RemoteAddr) // 连接到源服务器 443 端口的 TCP serverConn, err := net.DialTimeout("tcp",...
package main import ( "app-auth/auth" "app-auth/config" "app-auth/controllers" "app-auth/schedule" "log" "os" "regexp" "github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) func main() { // instantiate the server e := echo.New() e.HideBanne...
package main import ( "context" "log" "os" "sync" ) var ( processor *Processor ) func init() { processor = NewProcessor() } type Processor struct { ctx context.Context tasks map[string]*TaskProfile register chan *TaskProfile unregister chan *TaskProfile close chan error hub *Hub lock ...
package main import ( "fmt" "math/rand" "time" ) func main() { //1.添加字符A-Z,并输出================== var myChars [26]byte for i := 0; i < 26; i++ { myChars[i] = 'A' + byte(i) } for i := 0; i < 26; i++ { fmt.Printf("%c", myChars[i]) } //2.取出数组内最大数,和其索引================== var intArr = [...]int{1, -1, 3, 80, 1...
package productsrv import ( "context" "github.com/jackc/pgx/v4/pgxpool" "github.com/amanbolat/furutsu/datastore" "github.com/amanbolat/furutsu/internal/product" ) type Service struct { dbConn *pgxpool.Pool } func NewProductService(conn *pgxpool.Pool) *Service { return &Service{dbConn: conn} } func (s Servic...
package main import "testing" func TestArenaToStringMultiColumn(t *testing.T) { arena := Arena{[]Column{ Column{[]string{".", " ", ":", "T"}}, Column{[]string{".", " ", ":", "T"}}, }} expected := "+--+\n|..|\n| |\n|::|\n|TT|\n+--+\n" if arena.toString() != expected { t.Error(arena.toString()) } } func ...
package groups import ( "fmt" "docktor/server/middleware" "docktor/server/types" "github.com/labstack/echo/v4" ) // AddRoute add route on echo func AddRoute(e *echo.Group) { groups := e.Group("/groups") // Basic daemon request groups.GET("", getAllWithDaemons) groups.POST("", save) groups.GET(fmt.Sprintf(...
package object // SimplifiedArtist represents SimplifiedArtistObject // Link: https://developer.spotify.com/documentation/web-api/reference/#object-simplifiedartistobject type SimplifiedArtist struct { Name string `json:"name"` ID string `json:"id"` ExternalURLs ExternalURL `json:"extern...
package subspace /* To prevent namespace collision between consumer app/v1, we define type "space". A Space can only be generated by the keeper, and the keeper checks the existence of the space having the same name before generating the space. Consumer app/v1 must take a space (via Keeper.Subspace), not the keeper it...
// Hands-on exercise #4 // Fix the race condition you created in the previous exercise by using a mutex // it makes sense to remove runtime.Gosched() package main import ( "fmt" "sync" ) var incrementer int var wg sync.WaitGroup var mu sync.Mutex func increment() { mu.Lock() v := incrementer v = v + 1 increme...
package models import ( "gorm.io/gorm" ) type Book struct { gorm.Model Id int `gorm:"primaryKey` Title string `json:"title" form:"title"` Author string `json:"author" form:"author"` Content string `json:"content" form: "content"` } type BookAPI struct { Id int `json:"id" form:"id"` Title str...
package main import ( "errors" "fmt" "strconv" "time" // "github.com/DAddYE/vips" "github.com/daddye/vips" "github.com/google/uuid" "io/ioutil" "log" "net/http" // "net/url" "encoding/json" "os" "strings" ) // TrackerJohn type Patient struct { //Personal Information FirstName string LastName string...
package outputs import ( "bytes" "embed" "html/template" "streamjury/gameplay" ) const ( filename = "round.html" ) //go:embed round.html var dataTemplateFS embed.FS func PublishResultsInHTML(g gameplay.GamePlay) ([]byte, error) { var err error var tpl *template.Template var buf bytes.Buffer = bytes.Buffer{}...
package dl import ( "os" "testing" ) func TestGetFile(t *testing.T) { url := "https://gist.githubusercontent.com/phillipsj/07fed8ce06f932c19ab7613d8426d922/raw/13d3fc0ca54d136ad5744fd4448b65dbc87f32dc/random.txt" file := "getfile.txt" if err := GetFile(url, file); err != nil { t.Errorf("Error downloading the f...
package services import ( "encoding/json" "fmt" "net/http" "cartracker.api/common" ) // Authorized function func Authorized(w http.ResponseWriter, r *http.Request) (*common.AuthUserInfo, bool, error) { session, err := common.OAuthStore.Get(r, "session_cookie") if err != nil { fmt.Fprintln(w, "aborted") ret...
package websocket import ( "fmt" "github.com/gorilla/websocket" "github.com/tiagorlampert/CHAOS/client/app/environment" "net/http" "net/url" "strings" ) func NewConnection(configuration *environment.Configuration, clientID string) (*websocket.Conn, error) { host := configuration.Server.Address host = strings....
// +build integration package disgord import ( "context" "os" "sync" "testing" "time" ) var token = os.Getenv("DISGORD_TOKEN_INTEGRATION_TEST") var guildTypical = struct { ID Snowflake VoiceChannelGeneral Snowflake VoiceChannelOther1 Snowflake VoiceChannelOther2 Snowflake }{ ID: ...
// Copyright 2020 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package backup import ( "archive/tar" "bytes" "compress/gzip" "fmt" "io" "os" "path/filepath" "strings" "github.com/clivern/walrus/core/util" ) // Backup creat...
package beacon // RandomnessType specifies a type of randomness. type RandomnessType int64 const ( RandomnessTypeElectionProofProduction RandomnessType = 1 + iota )
// Copyright 2016-2017 The psh Authors. All rights reserved. package psh import ( "bytes" "fmt" ) const ( // SegmentCWDBackground is the background color to use SegmentCWDBackground = 237 // #3a3a3a ) // SegmentCWD implements the current working directory partial of the prompt. // // It renders the current work...
package polls import ( "sync" "github.com/Nv7-Github/Nv7Haven/db" "github.com/Nv7-Github/Nv7Haven/eod/base" "github.com/Nv7-Github/Nv7Haven/eod/types" "github.com/bwmarrin/discordgo" ) type Polls struct { dat map[string]types.ServerData lock *sync.RWMutex dg *discordgo.Session db *db.DB base *base.Bas...
// This gocode'll handle the master-side of the distributed system package main import ( "encoding/gob" "log" "net" "os" ) type P struct { M, N int64 } func Master(args []string) { Min_slaves := args[0] List_Port := args[1] log.Println("Hello world from the master") log.Println("I need ", Min_slaves, " t...