text
stringlengths
11
4.05M
package routers import ( "TestWeb/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/getUser", &controllers.GetController{}) beego.Router("/get", &controllers.ObjectController{}) beego.Router("/console", &controllers.ConsoleController{})...
package acmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00100103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:acmt.001.001.03 Document"` Message *AccountOpeningInstructionV03 `xml:"AcctOpngInstr"` } func (d *Document00100...
package debug import ( "github.com/davecgh/go-spew/spew" ) func Dump(n interface{}) { spew.Dump(n) }
package setupserver import ( "crypto/tls" "crypto/x509" "errors" "flag" "fmt" "io/ioutil" "os" "path" "time" "github.com/Cloud-Foundations/Dominator/lib/format" "github.com/Cloud-Foundations/Dominator/lib/log/nulllogger" "github.com/Cloud-Foundations/Dominator/lib/srpc" ) var ( caFile = flag.String("CAf...
package utils import ( "encoding/json" ) type converter interface { SavetoJson }
/* Go Language Raspberry Pi Interface (c) Copyright David Thorpe 2016-2017 All Rights Reserved Documentation http://djthorpe.github.io/gopi/ For Licensing and Usage information, please see LICENSE.md */ package bme280 import ( "fmt" "math" "time" gopi "github.com/djthorpe/gopi" sensors "github.com/djth...
package typeDefine import ( // "fmt" "net" ) const MAXN = 10 type TotalUser struct { OnlineUser []*User Mp map[string]*net.TCPConn } type User struct { Mes chan string Name string } func (user *TotalUser) AddUser(name string, conn net.Conn) { if user.ExitUser(name, "") { conn.Write([]byte("unsucc...
package main import ( "fmt" "log" "github.com/mattn/go-tty" ) func readRune() { tty, err := tty.Open() if err != nil { log.Fatal(err) } defer tty.Close() L: for { fmt.Print("tty:>") r, err := tty.ReadRune() if err != nil { log.Fatal(err) } switch r { case 'q': break L default: fmt.P...
package mat import ( "fmt" "math" "strconv" "strings" "sync" ) type Canvas struct { W int H int MaxIndex int Pixels []Tuple4 } func NewCanvas(w int, h int) *Canvas { pixels := make([]Tuple4, w*h) for i, _ := range pixels { pixels[i] = NewColor(0, 0, 0) } return &Canvas{W: w, H: h, Pixe...
package array import "testing" func TestArrayInit(t *testing.T) { var arr [3]int arr1 := [4]int{1, 2, 3, 4} arr3 := [...]int{12, 14} arr1[2] = 5 t.Log(arr[1]) t.Log(arr1, arr3) } func TestArrayTravel(t *testing.T) { arr3 := [...]int{12, 14} for idx, e := range arr3 { t.Log(idx, e) } } func TestArratSec...
package mhfpacket import ( "github.com/Andoryuuta/Erupe/network" "github.com/Andoryuuta/Erupe/network/clientctx" "github.com/Andoryuuta/byteframe" ) // MsgSysPositionObject represents the MSG_SYS_POSITION_OBJECT type MsgSysPositionObject struct { ObjID uint32 X, Y, Z float32 } // Opcode returns the ID associa...
package mysqldb import ( "context" "time" ) // DeviceOrganizationBinding Device和组织关联 type DeviceOrganizationBinding struct { DeviceID int `gorm:"column:device_id"` OrganizationID int `gorm:"column:organization_id"` CreatedAt time.Time // 创建时间 UpdatedAt time.Time // 更新时间 } // TableNa...
package main import ( "time" ) func UserRecoverPassword(host string, email string) ResponseStr { user := dbListUsers(email) if user.Module == "" { return ResponseStr{"error", "Email account not found."} } token := UtilTokenGenerator() dbUpdateBack("UPDATE Users SET TempChangePass='" + UtilCreateHash(token...
package responder import ( "encoding/json" "net/http" ) func ResponseOK(rw http.ResponseWriter, body interface{}) error { rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusOK) return json.NewEncoder(rw).Encode(body) }
package utils import ( "regexp" "strings" ) // MatchOneOf match one of the patterns func MatchOneOf(text string, patterns ...string) []string { var ( re *regexp.Regexp value []string ) for _, pattern := range patterns { re = regexp.MustCompile(pattern) value = re.FindStringSubmatch(text...
package dict func init() { var compressedData = []byte{ 0x78, 0xDA, 0xEC, 0xDA, 0x05, 0x97, 0x9B, 0xDA, 0xDB, 0xB0, 0x71, 0xDA, 0x49, 0xDD, 0xDD, 0xDB, 0x99, 0xE9, 0xA4, 0x2E, 0x4C, 0xA7, 0x6E, 0x53, 0xF7, 0x26, 0x84, 0x24, 0x40, 0x20, 0x24, 0x21, 0x01, 0x82, 0x24, 0x58, 0xEA, 0x2E, 0xA7, 0x72, 0xEA, 0xEE, 0xEE...
use reference::Ref; use memory::ThunkMemory; pub trait Stored { fn stored(&self, m: &mut ThunkMemory) -> Ref; } // impl<&T> Stored for &T where T: Stored { // fn stored(&self, m: &ThunkMemory) -> Ref { // } // } impl Stored for String { fn stored(&self, m: &mut ThunkMemory) -> Ref { for c in self.chars...
package db import ( "context" "database/sql" "go-cqrs/model" "go-cqrs/util" _ "github.com/lib/pq" // needed for improve Scan func ) // PostgresRepository struct type PostgresRepository struct { db *sql.DB } // OpenConnection to open db connection func OpenConnection(url string) (*PostgresRepository, error) { ...
package postgresql import ( "context" "fmt" "time" "github.com/google/uuid" "github.com/Mindslave/skade/backend/internal/entities" ) //StoreFile is used to store files uploaded to skate func (r* Repo) StoreFile(ctx context.Context, arg entities.DbStoreFileParams) (error) { var file entities.File uuid, err :...
package cmd import ( "bytes" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "github.com/ghodss/yaml" "github.com/spf13/cobra" go_prompt "github.com/c-bata/go-prompt" "github.com/a8uhnf/suich/pkg/utils" ) var kubeConfigPath = filepath.Join(os.Getenv("HOME"), ".kube", "config") var prompt bool var...
package news import ( "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "ions_zhiliao/models/news" "ions_zhiliao/utils" "math" "strconv" "time" ) type NewsController struct { beego.Controller } func (n *NewsController) Get() { o := orm.NewOrm() var news_data...
/** *@Author: haoxiongxiao *@Date: 2019/4/1 *@Description: CREATE GO FILE admin */ package admin import ( "github.com/kataras/iris" "github.com/kataras/iris/mvc" ) type IndexController struct { Ctx iris.Context } var commandNotLoginIndex = mvc.View{ Name: "index.html", } func NewIndexController() *IndexControl...
package twingo import ( "github.com/op/go-logging" ) //===================================================================================================================== type MarketDataEventsDispatcher struct { logger *logging.Logger ingressCh chan *MarketDataMessage egressTradeChs []chan <- *MarketTimedEve...
/* 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...
// // DISCLAIMER // // Copyright 2017 ArangoDB GmbH, Cologne, Germany // // 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 require...
package caddynet import ( // plug in the server _ "github.com/pieterlouw/caddy-net/caddynet/netserver" // // plug in the standard directives _ "github.com/pieterlouw/caddy-net/caddynet/host" )
package dbstore import ( "context" "database/sql" "encoding/json" "time" "github.com/devopstoday11/tarian/pkg/tarianpb" "github.com/driftprogramming/pgxpoolmock" uuid "github.com/satori/go.uuid" "google.golang.org/protobuf/types/known/timestamppb" "github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4/pgxpool"...
package handler import ( "context" "errors" "github.com/dkorittki/loago/pkg/api/v1" "github.com/rs/zerolog/log" "google.golang.org/grpc/peer" ) // Ping responds with a PingResponse message to incoming ping requests. func (w *Worker) Ping(ctx context.Context, req *api.PingRequest) (*api.PingResponse,...
package model import ( "github.com/jinzhu/gorm" "log" ) type Wait struct { BaseModel OldWaitSql *string `gorm:"column:old_wait_sql" json:"old_wait_sql"` OldWait *string `gorm:"column:old_wait" json:"old_wait"` OldWaitTime *string `gorm:"column:old_wait_time" json:"old_wait_time"` OldWaitMysql *int `...
/* * Copyright (c) 2019. Alexey Shtepa <as.shtepa@gmail.com> LICENSE MIT * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. */ package bindata import ( "unsafe" ) func memdump(v interface{}) (slice []byte) { vptr, size := inspec...
package dic import ( "bytes" "encoding/gob" "github.com/soundTricker/kagome/data" ) type CharacterClass byte const ( DEFAULT CharacterClass = 0 SPACE CharacterClass = 1 NUMERIC CharacterClass = 4 HIRAGANA CharacterClass = 6 KATAKANA CharacterClass = 7 KANJINUMERIC CharacterClass = ...
package util var KListenPort string = "" var KTraceDataPort string = "2345" var KSamplingPort string = "" var KClientProcessPort1 string = "8000" var KClientProcessPort2 string = "8001" var KBackendProcessPort string = "8002" var KBatchSize int = 20000 var KProcessCount int = 2 var KBatchCount int = 300 var KClientCon...
package retry import ( "fmt" "testing" "time" ) func TestRetry(t *testing.T) { fn := func() error { return fmt.Errorf("timeout") } if err := Retry(1, 2*time.Second, fn); err != nil { t.Fatal(err) } } func TestRetryWithFuncArgs(t *testing.T) { // closure fn fn := func() error { name := "tom" // arg...
package main import ( "fmt" "io/ioutil" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request){ //fmt.Fprintf(w, "Hello World: " + r.RequestURI) resp, err := http.Get("https://www.nrk.no" + r.RequestURI) if err != nil { print(err) } defer resp.Body.Close() body, err := ...
package main import ( "flag" "fmt" "github.com/st3redstripe/termbank/domain" "github.com/st3redstripe/termbank/renderer" ) var ( helpFlag = flag.Bool("help", false, "Account") ) func main() { flag.Parse() if *helpFlag == true { renderer.PrintHelp() } else { inititialise() } } func inititialise() { cr...
//Here are integration tests for project. Following test load some data and then do multiple selects to check //if every integration is working package integrationTests import ( "github.com/d-d-j/ddj_master/dto" "encoding/json" "fmt" . "github.com/ahmetalpbalkan/go-linq" "io/ioutil" "math" "math/rand" "net/htt...
package gocpy /* #include "Python.h" */ import "C" //PyEval_GetBuiltins : https://docs.python.org/3/c-api/reflection.html?highlight=reflection#c.PyEval_GetBuiltins func PyEval_GetBuiltins() *PyObject { return togo(C.PyEval_GetBuiltins()) } //PyEval_GetLocals : https://docs.python.org/3/c-api/reflection.html?highlig...
package main import ( f "fmt" "runtime" "sync" "time" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) Condition() f.Println("-------------------") Mutex() } func Condition() { data := 0 go func() { for i := 0; i < 3; i++ { data += 1 f.Println("write : ", data) time.Sleep(10 * time.Milli...
package main import ( "fmt" "sort" ) func main() { s := []int{-1, 2, 1, -4} fmt.Println(threeSumClosest(s, 1)) } func threeSumClosest(nums []int, target int) int { n := len(nums) sort.Ints(nums) res := nums[0] + nums[1] + nums[2] for i := 0; i < n-2; i++ { l, r := i+1, n-1 for l < r { tmp := nums[i]...
package main import ( "fmt" "time" ) var a int func init() { a = 1 } var c = make(chan int, 10) var b string func f() { b = "hello, world" c <- 0 } func Foo(n int) int { fmt.Println(n) return n } /** * created: 2019/7/15 9:26 * By Will Fan */ func main() { //fmt.Println(a) go func() { fmt.Println(a...
package main import ( "flag" "fmt" "os" "path" "strings" ) const ( INDENT = " " ) var basePath string func init() { flag.StringVar(&basePath, "p", "", "path you want to show") } func showDirs(bashPath string, prefix string, showAll bool) error { base, err := os.Open(bashPath) if err != nil { return err ...
package main import ( "fmt" log "github.com/Sirupsen/logrus" "github.com/mitchellh/mapstructure" "github.com/ovh/cds/sdk" "github.com/ovh/cds/sdk/event" "strings" ) var mapPb map[string]string func consumeFromKafka(kafka, topic, group, username, password string) { log.Info("Init kafka consumer") mapPb = mak...
package crawler import ( "WikiGo/db" "WikiGo/parser" "WikiGo/wikipage" "errors" "fmt" "io/ioutil" "net/http" "sync" "time" ) // FileLimit : max number of files that can be open at once const ( FileLimit = 1000 ) // Crawler : struct that has a source and destination page with a map cache of shortest distanc...
package cmd import ( "fmt" "os" "github.com/spf13/cobra" "github.com/kainosnoema/terracost-cli/plan" "github.com/kainosnoema/terracost-cli/terraform" ) func init() { rootCmd.AddCommand(estimateCmd) } var estimateCmd = &cobra.Command{ Use: "estimate [planfile]", Short: "Plan and estimate costs for a Terra...
package storage import ( "github.com/danil-lashin/twitter-rewards/config" "github.com/syndtr/goleveldb/leveldb" ) type DB struct { ldb *leveldb.DB } func NewDB(cfg *config.Config) *DB { db, err := leveldb.OpenFile("db/", nil) if err != nil { panic(err) } return &DB{ ldb: db, } } func (db *DB) IsUserExi...
package controller import ( cache "Golang-challenge/pkg" "Golang-challenge/service" "time" ) var cacheInstance *cache.TransparentCache type Controller struct { } func NewController() *Controller { if cacheInstance == nil { cacheInstance = cache.NewTransparentCache(service.NewPriceService(), time.Minute) } r...
package detector import ( "fmt" "github.com/wata727/tflint/issue" "github.com/wata727/tflint/schema" ) type AwsInstanceInvalidTypeDetector struct { *Detector IssueType string Target string DeepCheck bool instanceTypes map[string]bool } func (d *Detector) CreateAwsInstanceInvalidTypeDetector()...
package schema import () type Errors struct { Messages map[string]string } func NewErrors() *Errors { errors := &Errors{ Messages: map[string]string{}, } return errors } func (errors *Errors) Add(field string, message string) { errors.Messages[field] = message } func (errors *Errors) Clear() { errors.Mess...
/* * @Description: In User Settings Edit * @Author: your name * @Date: 2019-08-17 15:52:08 * @LastEditTime: 2019-08-22 12:54:36 * @LastEditors: Please set LastEditors */ package main import ( "encoding/json" "net/http" "strconv" "github.com/yuwe1/shuxiang/common/dber" "github.com/yuwe1/shuxiang/common/log"...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //448. Find All Numbers Disappeared in an Array //Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and oth...
package bridge type ErrorType int const ( ErrUnsupported ErrorType = iota ErrServerError ErrFailed ) type Error struct { typ ErrorType } func NewError(typ ErrorType) *Error { return &Error{typ} } func (e *Error) Type() ErrorType { return e.typ }
package mysqldb import ( "errors" "server" "server/libs/log" ) var ( db *MysqlDB ) type MysqlDB struct { pools int sql SqlWrapper Account *Account DBRaw *Database dbname string ds string nameunique bool //wg util.WaitGroupWrapper limit int } func (self *MysqlDB) Ini...
package invoice import ( "time" ) type PublishedState struct { } func (s PublishedState) State(i *Invoice) State { now := time.Now() if i.DueDate.Before(now) { return Failed } return Published } func (s PublishedState) Publish(i *Invoice) error { return i.SetState(&PublishedState{}) } func (s PublishedStat...
package catalog import ( "context" "errors" "fmt" "testing" "time" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" utilerrors "k8s.io/apimachinery/pkg/util/errors" utilclocktesting "k8s.io/utils/clock/testing"...
package ws import ( "github.com/game-explorer/animal-chess-server/model" "golang.org/x/net/websocket" ) func SendMessage(c *websocket.Conn, msg *model.Message) (err error) { err = websocket.Message.Send(c, string(msg.Marshal())) if err != nil { return } return } func SendMessageRaw(c *websocket.Conn, types ...
package main import ( "encoding/csv" "fmt" "io" "log" "os" ) func main() { // input file fh, err := os.Open("perf.csv") if err != nil { log.Fatal(err) } defer fh.Close() // csv read reader := csv.NewReader(fp) reader.LazyQuotes = true rows, err := reader.ReadAll() if err != nil...
package main import ( "./entities" "fmt" ) func main() { // Admin 中包含一个inner type: user,user中定义的都是exported field,可以直接通过outer type来访问这些field admin := entities.Admin{ Right: 10, } admin.Name = "hahaha" admin.Email = "123@123.com" fmt.Printf("admin info: [%v] \n", admin) }
package gcp import ( "context" "net/http" "sort" "time" survey "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" "github.com/pkg/errors" "google.golang.org/api/googleapi" ) // GetBaseDomain returns a base domain chosen from among the project's public DNS zones. func GetBaseDomain(pro...
package http import ( "errors" "fmt" "log" "net" "net/http" "reflect" "regexp" "strings" "sync" "time" "github.com/valyala/fasthttp" "github.com/savsgio/gotils" ) type ( cleanPathBuffer struct { n int r int w int trailing bool buf []byte } Router struct { prefix...
package manager import ( "sync" "github.com/go-xorm/xorm" "github.com/labstack/echo" "os" "github.com/labstack/echo/middleware" "monitoring/internal" "strconv" ) type manager struct { db *xorm.Engine web *echo.Echo config *internal.Configuration } func (c *manager)init() { // Echo init fp, _ := os...
package utils import ( "log" "fmt" "os" "net" ) func GetOutboundIPAddr() (string){ var allIPAddr string ifaces, err := net.Interfaces() if err != nil { log.Fatal("Error retrieving IP Addrs:",err) return "" } for _, i := range ifaces { addrs, err := i.Addrs(...
package loan import ( "fmt" "loanprocessing/custom" "math" "sync" "time" ) // Loan stores details of the loan that is processed currently. type Loan struct { Principal float64 `json:"initialAmount" binding:"required,numeric,min=1"` Rate float32 `json:"annualRate" binding:"required,numeric,min=...
package log import ( "github.com/riposa/utils/errors" "testing" ) func TestLogger_EnableDebug(t *testing.T) { logger := New() logger.EnableDebug() logger.Info("info") logger.Debug("debug") logger.DisableDebug() logger.Info("info") logger.Debug("debug") } func TestLogger_Exception(t *testing.T) { logger := ...
package repo import ( "fmt" "strings" "github.com/abhinav/git-pr/gateway" ) var _prefixes = []string{ "ssh://git@github.com/", "git@github.com:", "https://github.com/", } // Guess determines the Repo name based on the current Git repository's remotes. func Guess(git gateway.Git) (*Repo, error) { url, err := ...
package yaas import "testing" func TestInverseYes(t *testing.T) { want := YesString(noConst) got, err := Inverse(Yes()) if got != want { t.Errorf("got %q, want %q, err %q", got, want, err) } } func TestInverseNo(t *testing.T) { want := YesString(yesConst) got, err := Inverse(Inverse(Yes())) if go...
package file import ( "time" "os" "io/ioutil" "path/filepath" ) type FileInfo struct { Name string Path string Size int64 MTime time.Time CTime time.Duration } func Exist(filename string) bool { _, err := os.Stat(filename) return err == nil || os.IsExist(err) } /*获取文件夹下所有文件*/ func GetFileList(dir string,...
/* Copyright 2018 Pressinfra SRL. 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...
package externalservice import ( "github.com/magiconair/properties/assert" "testing" ) func TestMainFunction(t *testing.T) { assert.Panic(t, testFunction, "unsupported protocol scheme \"\"") } func testFunction() { googleDependency := GoogleDependency{} googleDependency.CallDependencies() }
package main import "fmt" func process(a, b []int) (int, int) { var pointA, pointB int for i := 0; i < len(a); i++ { if a[i] > b[i] { pointA++ } if a[i] < b[i] { pointB++ } } return pointA, pointB } func main() { a := make([]int, 3) b := ...
package util import "os" // GetEnv returns the value for the key, If the key doesn't exist, returns defValue. func GetEnv(key, defValue string) string { value := os.Getenv(key) if len(value) == 0 { return defValue } return value }
package main import ( "net/http" "fmt" ) func main() { http.HandleFunc("/",foo) http.HandleFunc("/bar",bar) http.Handle("/favicon.ico",http.NotFoundHandler()) http.ListenAndServe(":8080",nil) } func foo(w http.ResponseWriter,r *http.Request){ fmt.Println("method(foo) is:",r.Method) } func bar(w http.Respo...
package controllers import ( "github.com/astaxie/beego" "scholarship/models" "scholarship/middlewares" ) // Operations about object type SignatureController struct { beego.Controller } // @Title Sign // @Description sign json // @Param name query string true "the username you want to sign" // @Param password ...
package utils type HttpConfig struct { Addr string `json:"address"` Port int `json:"port"` ReadTimeout int `json:"read_timeout"` WriteTimeout int `json:"write_timeout"` } var ( httpConfig *HttpConfig ) func InitHttp(httpConf HttpConfig) { httpConfig = &httpConf if httpConfig.Addr == ...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
package cmd import ( log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) // NewRootCmd returns the root authelia-scripts cmd. func NewRootCmd() (cmd *cobra.Command) { cmd = &cobra.Command{ Use: "authelia-scripts", Short: cmdRootShort, Long: cmdRootLong, Example: cmdRootExample, DisableA...
package repository import ( "context" "github.com/indrasaputra/aptx/entity" ) // InsertURLDatabase defines the interface to insert a new URL to the database. type InsertURLDatabase interface { // Insert inserts a new URL into the database. // It must handle if the data already exists. Insert(ctx context.Context...
package backup import ( "fmt" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" api "github.com/Percona-Lab/percona-xtradb-cluster-operator/pkg/apis/pxc/v1alpha1" ) // PVC returns the list of PersistentVolumeClaims for the backups func PVC(cr *api....
package goutils import "image" const darkness = 60 func checkDarkness(p Pixel) bool { var r, g, b int if p.R <= darkness { r = 1 } if p.G <= darkness { g = 1 } if p.B <= darkness { b = 1 } if r+g+b == 3 { return true } return false } // GetPixels gets the bi-dimensional pixel array func GetPixels...
/* nighthawkapi.routes.apiroutes; */ package routes import ( "fmt" "net/http" api "nighthawkapi/api/core" "nighthawkapi/api/handlers/analyzer" "nighthawkapi/api/handlers/audit" "nighthawkapi/api/handlers/auth" config "nighthawkapi/api/handlers/config" "nighthawkapi/api/handlers/delete" "nighthawkapi/api/...
package log_streamer import "unicode/utf8" type streamDestination struct { guid string emitter func(string, string) buffer []byte } func (destination *streamDestination) Write(data []byte) (int, error) { destination.processMessage(string(data)) return len(data), nil } func (destination *streamDestination) fl...
// +build windows // +build !linux // +build !darwin package distro func Vendor() string { return "windows" } func Name() string { return "Microsoft Windows" }
package main import ( "errors" "fmt" "sync" ) type Teacher struct { rating float64 totalRating int64 } type Student struct { rating int64 timeTaken int } func (stud *Student) GiveRating() int64 { stud.rating = 10 return stud.rating } // CalcRating calculates teacher ratings func (tch *Teacher) Cal...
package main import ( "{@project}/src/common" "{@project}/src/controllers" "{@project}/src/logic" "{@project}/src/models" "flag" "fmt" "github.com/ztxmao/vii/frame" "github.com/ztxmao/vii/frame/router" "io/ioutil" "os" "path" "strconv" "time" ) func main() { defer func() { managePid(false) //删除pid文件 ...
package demo2 import ( "errors" "fmt" "math/big" "regexp" "strings" "speter.net/go/exp/math/dec/inf" ) // International System of Units: // (Metric prefix) // https://en.wikipedia.org/wiki/Metric_prefix // // Examples: // 1.5 will be serialized as "1500M" or "1500m" // 1.5Gi will be serialized as "1536Mi" ...
package wire import ( "bytes" "io" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol" ) var _ = Describe("ACK Frame (for IETF QUIC)", func() { Context("parsing", func() { It("parses an ACK frame without any ranges",...
package main import ( "fmt" "github.com/ugorji/go/codec" "io/ioutil" "reflect" ) // create and configure Handle var ( js codec.JsonHandle ) type RestApiV2 struct { Last string `json:"last"` First string `json:"first"` } func main() { js.SliceType = reflect.TypeOf([]interface{}(nil)) var restapi []interfac...
package command import ( "encoding/json" "fmt" "regexp" "github.com/jclem/graphsh/types" ) var headerPattern = regexp.MustCompile("^(.+): (.+)$") var queryPattern = regexp.MustCompile("^{.+}$") // Query executes a GraphQL query type Query struct { query string } func testQuery(input string) (Command, error) {...
package timehelper import ( "errors" "time" ) var time0 time.Time // Time0 returns zero Time. func Time0() time.Time { return time0 } // IntAsMonth converts int into time.Month with range checking. func IntAsMonth(month int) (time.Month, error) { if month < 1 || month > 12 { return time.Month(0), errors.New("...
package data import ( "bytes" "fmt" "log" "testing" "gopkg.in/go-playground/assert.v1" ) func TestNewPrices(t *testing.T) { l := log.New(bytes.NewBufferString(""), "", log.LstdFlags) tests := []struct { name string source string expErrMsg string }{ { name: "ok", source: "https...
/* Convert JSON (key/value pairs) to two native arrays, one array of keys and another of values, in your language. var X = '{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f9","g":"g2","h":"h1"}'; The value array could be an array of strings or integers. So we need two functions keys & vals, returning native arrays o...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package maildir import ( "fmt" "os" "path" "testing" "github.com/amalfra/maildir/lib" ) var mailDir string var testData string var maildir *Maildir func cleanMaildir() { err := os.RemoveAll(mailDir) if err != nil { fmt.Fprintln(os.Stderr, "Failed to clean maildir folder") os.Exit(1) } } func init() { ...
// Copyright 2015-2018 trivago N.V. // // 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 main import ( "bytes" "encoding/json" "fmt" "golang.org/x/net/websocket" "io/ioutil" "net/http" "strconv" "time" ) type loginRequest struct { Username string `json:"username"` Password string `json:"password"` } type loginResponse struct { Message string `json:"message"` Status int32 `json:"statu...
package graph type Node struct { Val string } type Graph struct { nodes []Node edges map[Node][]Node } func AddNode(g *Graph, n Node) { if !contains(g.nodes, n) { g.nodes = append(g.nodes, n) } } func Nodes(g Graph) []Node { return g.nodes } func Edges(g Graph) map[Node][]Node { return g.edges } func Add...
package server import ( "math/big" "net/http" "time" "github.com/go-chi/chi/middleware" "github.com/stellar/go/support/log" ) func loggerMiddleware(requestIDKey interface{}, next http.Handler, w http.ResponseWriter, r *http.Request) { requestLog := log.WithFields(log.F{ "request_id": r.Context().Value(reques...
package hnb import ( appComm "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/msp" "encoding/json" "github.com/pkg/errors" "sort" "strconv" ) type VoteInfo struct { FromAddr []byte `json:"fromAddr"` Candidate []byte `json:"candidate"` VotingPower int64 `json:...
package compute import ( "encoding/json" "fmt" "net/http" "net/url" ) // SSLOffloadProfile represents an SSL-offload profile. type SSLOffloadProfile struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"descripti...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
package main import "strconv" func restoreIpAddresses(s string) []string { var res []string dfs93(&res, s, "", 4) return res } func judgeIP(ip string) int { if len(ip) > 1 { if ip[0] == '0' { return -1 } else { res, _ := strconv.Atoi(ip) if res > 255 { return -1 } return res } } else { ...