text
stringlengths
11
4.05M
package db import ( "log" "testing" ) const ( Host string = "127.0.0.1:3306" User string = "root" Password string = "huang03" Db string = "test" ) //查询单条数据 func TestFind(t *testing.T) { mysql := NewMySQL(Host, User, Password, Db) mysql.Table("user") mysql.Alias("T1") mysql.Order("id desc") m...
package handlers import ( "log" "net/http" "os" "github.com/IsaiasMorochi/twitter-clone-backend/middleware" "github.com/IsaiasMorochi/twitter-clone-backend/routers" "github.com/gorilla/mux" "github.com/rs/cors" ) /*Manejadores seteo mi puerto, el handler y pongo a escuchar el servidor*/ func Manejadores() { ...
package types import ( "bytes" "encoding/hex" "encoding/json" "fmt" "github.com/reed/crypto" "strconv" "testing" ) func TestTx_GenerateID(t *testing.T) { id1, _ := hex.DecodeString("416c7cfb8a0836d51517b6ae32e0dee579a554f41c10448da847f0888b76881e") id2, _ := hex.DecodeString("1a946d5a05761732ae162a886a767fde...
package clear import ( "os" ) const workDir = "/etc/kubernetes" func Clean() { os.RemoveAll(workDir) }
package cfmysql import "net" //go:generate counterfeiter . NetWrapper type NetWrapper interface { Dial(network, address string) (net.Conn, error) Close(conn net.Conn) error } func NewNetWrapper() NetWrapper { return new(netWrapper) } type netWrapper struct{} func (self *netWrapper) Dial(network, address string)...
package flats import ( "fmt" "github.com/dgraph-io/experiments/flats/fuids" flatbuffers "github.com/google/flatbuffers/go" ) func ToAndFrom() { } func ToAndFromProto(uids []uint64) (error, int) { var ul UidList ul.Uid = make([]uint64, len(uids)) copy(ul.Uid, uids) data, err := ul.Marshal() if err != nil { ...
package padding import ( "strings" "unicode/utf8" ) // A ZipCode structure type ZipCode struct { string } // MarshalCSV returns the zip code unchanged func (zip *ZipCode) MarshalCSV() (string, error) { return zip.string, nil } // UnmarshalCSV accepts a string and unmarshals the string into a zero // left-padded...
// Copyright 2023 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 http import ( "../dao" "../socket" "../types" "../utility" "encoding/json" "fmt" "github.com/gorilla/mux" "github.com/gorilla/sessions" _ "github.com/mattn/go-sqlite3" "html/template" "log" "math/rand" "net/http" "time" ) /* There are a lot of work remaining on this There is next to no securi...
package main import ( //"compress/gzip" // uncomment this line to use the gzip package "flag" "fmt" //"golang.org/x/net/html" // uncomment this line to use the html package "log" "net" "net/http" "os" "sync" "time" ) // Global constants const ( SERVERROR = 500 BADREQ = 400 MAX_OBJ_SIZE = 500*1024 MAX_C...
package factory //import ( // "errors" // "fmt" // // "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp" // "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/pkcs11" // "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/sw" //) // //const ( // PKCS11BasedFactoryName = "PKCS11" //) // //type PKCS11Factory struct{} // //func (f *PKCS11...
package mssql import _ "github.com/denisenkom/go-mssqldb"
package post import ( "database/sql" "fmt" "log" // driver import _ "github.com/go-sql-driver/mysql" ) var DB *sql.DB var TotalPosts int // connect to db and get all posts at start of the server func init() { ConnectDB() queryString := "select * from post order by id desc" rows, err := DB.Query(queryString...
package kademlia import ( "testing" ) func TestChannels(t *testing.T) { channels := NewChannelList() contacts := []Contact{ NewContact(NewKademliaID("FFFFFFFF00000000000000000000000000000000"), "127.0.0.1:8000"), NewContact(NewKademliaID("FFFFFFFF10000000000000000000000000000000"), "127.0.0.1:8000"), NewCon...
package service import ( "context" "fmt" "sync" "time" "github.com/geoirb/rss-aggregator/pkg/models" ) type storage interface { AddNews(newsField ...string) (err error) GetNews(ctx context.Context, title *string) (news []models.News, err error) } type source interface { GetDatа(url string) (data []byte, err...
package core import ( "fmt" "github.com/comdeng/HapGo/hapgo/logger" "reflect" "strings" "sync" ) type Controller struct { Name string Method string Req *HttpRequest Res *HttpResponse } type controllerInfo struct { Typ reflect.Type Name string Methods map[string]bool } func (ctrl *Controll...
package main import ( "container/list" "math" ) type treePair struct { node *TreeNode level int } func isEvenOddTree(root *TreeNode) bool { if root == nil { return true } l := list.New() l.PushBack(&treePair{ node: root, level: 0, }) for l.Len() > 0 { size := l.Len() preMin := math.MinInt32 ...
package set import ( "github.com/loginradius/lr-cli/cmd/set/accountPassword" "github.com/loginradius/lr-cli/cmd/set/domain" "github.com/loginradius/lr-cli/cmd/set/email" "github.com/loginradius/lr-cli/cmd/set/site" "github.com/loginradius/lr-cli/cmd/set/theme" "github.com/spf13/cobra" ) func NewsetCmd() *cobra...
package main import ( "flag" "fmt" "colorize" "id" "log" "net/http" "encoding/json" "tasks" "os" "path/filepath" "strings" "strconv" ) func RequestHanler(w http.ResponseWriter, r *http.Request) { var err error guid, _ := id.Next() w.Header().Set("X-REQUEST-ID", fmt.Sprintln(gu...
package externallogger type UpdateChannel <-chan *update func (up UpdateChannel) Clear() { for len(up) != 0 { <-up } } type UpdateConfig struct { Offset int Limit int Timeout int } func GenerateUpdateConfig(offset int) *UpdateConfig { return &UpdateConfig{ Offset: offset, Limit: 0, Timeout: 30, ...
package routers import ( "github.com/majid-cj/go-docker-mongo/apps" "github.com/majid-cj/go-docker-mongo/domain/entity" "github.com/majid-cj/go-docker-mongo/util" "github.com/kataras/iris/v12" ) // VerifyCodeRouter ... type VerifyCodeRouter struct { vca apps.VerifyCodeAppInterface } // NewVerifyCodeRouter ... ...
package frac // Fraction type. // See https://en.wikipedia.org/wiki/Fraction_%28mathematics%29. type Frac struct { Num int Den int }
package main import ( "github.com/Microkubes/jwt-issuer/app" "github.com/keitaroinc/goa" ) // JWTController implements the jwt resource. type JWTController struct { *goa.Controller } // NewJWTController creates a jwt controller. func NewJWTController(service *goa.Service) *JWTController { return &JWTController{C...
package main import ( "encoding/json" "fmt" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/timestamp" "github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer" ) func getChaincodeID(stub shim.ChaincodeStubInterface) (string, error) { sp, err := st...
package service import ( "net/http" "strings" "github.com/GXK666/eosTransfer/service/general" "github.com/GXK666/eosTransfer/transfer" "net" "context" "time" "github.com/gogo/gateway" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/kazegusuri/grpc-panic-handler" "github.com/spf13/viper" "g...
package utils import ( "crypto/sha1" "encoding/hex" ) func Sha1(str string) string { encryptInst := sha1.New() encryptInst.Write([]byte(str)) res := hex.EncodeToString(encryptInst.Sum(nil)) return res }
package saml import ( "time" ) func tearUp() { fakeNow := time.Now() Now = func() time.Time { return fakeNow } NewID = func() string { return "id-MOCKID" } }
package main import ( "fmt" "github.com/gocc/io" ) func main() { in := io.Input{} in.ReadSourceFile("test.txt") fmt.Printf("%d\n", in.Size) var i int64 fmt.Printf("%s\n", string(in.Buf)) for i=0; i<in.Size; i++ { fmt.Printf("%s\n", string(in.Buf[i])) } }
package domain type Movie struct { ID int Title string Language string } func (movie Movie) ValidTitle() bool { return movie.Title != "" } func (movie Movie) ValidLanguage() bool { return movie.Language != "" } type IContent interface { ValidTitle() bool ValidLanguage() bool }
package cmd import ( "fmt" "os" "github.com/hspazio/mint/configurations" "github.com/spf13/cobra" ) var configCmd = &cobra.Command{ Use: "config", Short: "Read/write configurations", Long: "Read/write configurations", Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: conf, e...
package merkle import ( "crypto/sha256" "crypto/sha512" "fmt" "hash" "io" "io/ioutil" "os" "testing" ) func TestMerkleHashWriterLargeChunk(t *testing.T) { // make a large enough test file of increments, corresponding to our blockSize bs := 512 * 1024 fh, err := ioutil.TempFile("", "merkleChunks.") if err ...
package main import ( "flag" "fmt" "io" "os" "strings" ) const ( // Production Values API_URL = "http://api.dnsmadeeasy.com/V1.2" // Development Values //API_URL = "http://api.sandbox.dnsmadeeasy.com/V1.2" ) var ( api_url string api_key string secret_key string outputType string debug ...
package main import ( "fmt" "log" "net/http" "strings" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() // разбор аргументов, необходимо вызвать самостоятельно fmt.Println(r.Form) // печать данных формы на стороне сервера fmt.Println("path", r.URL.Path) fmt.Println("scheme", r...
package main import ( "testing" ) func TestLongestCommonPrefix(t *testing.T) { strs := []string{ "hello world", "good good study,day day up", } if longestCommonPrefix(strs) != "" { t.Errorf("Test longestCommonPrefix fail.") } strs = []string{ "abstract", "abandon", } if longestCommonPrefix(strs) != ...
// Provide command-line arguments in the form of 'YYYY-mmm-DD' where: // - YYYY is a four digit year // - mmm is a three letter month abbreviation (Jan, Feb, Mar, et al) // - DD is a two digit date package main import ( "fmt" "os" "time" ) func main() { from, to := os.Args[1], os.Args[2] const shortForm = "2006...
package main import "fmt" func main() { const firstName string = "veto" fmt.Print("halo ", firstName, "!\n") const lastName = "firmandianta" fmt.Print("nice to meet you ", lastName, "!\n") }
// Copyright 2017 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 _19_Remove_Nth_Node_From_End_of_List /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func removeNthFromEnd(head *ListNode, n int) *ListNode { pre := &ListNode{Next: head} ret, fast, slow := ...
package hpke import ( "crypto/rand" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "os" "testing" "github.com/stretchr/testify/require" ) var ( fixedPSK = []byte{0x02, 0x47, 0xFD, 0x33, 0xB9, 0x13, 0x76, 0x0F, 0xA1, 0xFA, 0x51, 0xE1, 0x89, 0x2D, 0x9F, 0x30, 0x7F, 0xBE, 0x65, 0xEB, 0x17, 0x1E, 0x81, 0x...
package schema import ( "errors" "fmt" "log" ) /* 全局接口错误码定义 99开头的为系统级错误 */ // 错误码:10*** var ( // 通用错误码 SUCCESS = errors.New("00000:ok") FAIL = errors.New("99999:%s") MONGO_ERROR = errors.New("99100:mongo error -> %s") TCC_VALUE_ERROR = errors.New("99201:无效tcc值 %s") // 业务错误码 ) func P...
package futures import ( "testing" "github.com/stretchr/testify/suite" ) type longShortRatioServiceTestSuite struct { baseTestSuite } func TestLongShortRatioService(t *testing.T) { suite.Run(t, new(longShortRatioServiceTestSuite)) } func (s *longShortRatioServiceTestSuite) TestOpenInterestStatistics() { data ...
package service_test import ( "log" "net/http" "net/http/httptest" "strings" "testing" "github.com/danikarik/handler/pkg/service" ) func TestUrlHandlerRequest(t *testing.T) { ts := httptest.NewServer(service.New()) defer ts.Close() testCases := []struct { Name string Body string StatusCod...
package PDA import ( "fmt" "testing" ) func TestPDARulebook_NextConfig(t *testing.T) { rulebook := PDARulebook{rules: []PDARule{{ state: 1, character: '(', nextState: 2, popCharacter: '$', pushCharacters: []int32{'b', '$'}, }, { state: 2, character: '(', nextStat...
package main import ( "fmt" "os" ) func main() { var num var x for x == 0{ fmt.Println("Insira um número:") fmt.Fscanf(os.Stdin, "%d", &num) if num % 2 == 0{ n=n+1 } } fmt.Println("Agora sim podemos dividir igualmente entre mim e você!") }
package orm import ( "video_server/api/defs" "video_server/api/utils" ) func AddNewComments(vid string, aid int, content string) error { id, err := utils.NewUUID() if err != nil { return err } stmt, err := conn.Prepare("INSERT INTO comments (id, video_id, author_id, content) VALUES (?,?,?,?)") if err != ni...
package runner import ( "net" "github.com/go-stack/stack" "github.com/karlmutch/errors" ) // Functions related to networking needs for the runner // GetFreePort will find and return a port number that is found to be available // func GetFreePort(hint string) (port int, err errors.Error) { addr, errGo := net.Res...
package requestBody const ( TAG = "tag" TAG_AND = "tag_and" TAG_NOT = "tag_not" ALIAS = "alias" REGISTRATION_ID = "registration_id" SEGMENT = "segment" ABTEST = "abtest" ) type Audience struct { Object interface{} audience map[string][]string } func (...
package weapp import ( "fmt" "io" "net/http" "net/http/httptest" "os" "path" "testing" ) func TestBankCardByURL(t *testing.T) { server := http.NewServeMux() server.HandleFunc(apiBankcard, func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { t.Fatalf("Expect 'POST' get '%s'", r.Method) ...
package models import ( "fmt" "strings" "testing" "bytes" "github.com/ONSdigital/dp-map-renderer/testdata" . "github.com/smartystreets/goconvey/convey" ) // A Mock io.reader to trigger errors on reading type reader struct { } func (f reader) Read(bytes []byte) (int, error) { return 0, fmt.Errorf("Reader fai...
package main import "fmt" import "os" import "math" import "math/rand" import "strconv" func randTheta() float64{ return (rand.Float64() ) } func randomwalk(w int,h float64,d float64,n float64){ var c = float64(w) var a,b = c/2,h/2 var x,y float64 x=float64(a) y=float64(b) for i := 0...
/* * @lc app=leetcode.cn id=85 lang=golang * * [85] 最大矩形 */ package main import ( "fmt" ) // @lc code=start func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } /* 将每一列高度统计,将参数传递给84题 func largestRectangleArea(heights []int) int { var max...
/** * Problem from leetcode.com * * Balanced Binary Tree * * Given a binary tree, determine if it is height-balanced. * * For this problem, a height-balanced binary tree is defined as a binary tree * in which the depth of the two subtrees of every node never differ by more than 1. * */ /** * Definition for...
package store import ( "github.com/aws/aws-sdk-go/service/s3" "github.com/tobyjsullivan/event-store.v3/events" "github.com/aws/aws-sdk-go/aws" "encoding/base64" "bytes" "encoding/json" ) type Store struct { s3svc *s3.S3 bucket string } func NewS3Store(svc *s3.S3, bucket string) *Store...
package main import ( "encoding/json" "fmt" ) type person struct { Name string `json:"name"` Age int `json:"age"` } func main() { p1 := person{ Name: "周林", Age: 9000, } //序列化 b, _ := json.Marshal(p1) fmt.Println(string(b)) //反序列化 str := `{"name":"理想","age":18}` var p2 person ...
package crawlers type InfoarenaCrawler struct { }
package utils import ( "errors" "net" "net/http" "strconv" "time" ) var ( NotStartedErr = errors.New("not started") ) type Service interface { Router() http.Handler } type Options struct { ReadTimeout time.Duration WriteTimeout time.Duration } var defaultOpts = &Options{ ReadTimeout: time.Second, Writ...
package main //思路:push时,先将x加入q2,然后将q1元素依次加入q2,再把q2元素一次加入q1 //pop,top直接取q1即可 type MyStack struct { q1 []int q2 []int } /** Initialize your data structure here. */ func Constructor() MyStack { mystack := new(MyStack) mystack.q1 = make([]int, 0) mystack.q2 = make([]int, 0) return *mystack } /** Push element x ont...
package server import "server/libs/log" type Scheduler interface { SetSchedulerID(id int32) GetSchedulerID() int32 OnUpdate() } type SchedulerBase struct { id int32 } func (sb *SchedulerBase) SetSchedulerID(id int32) { sb.id = id } func (sb *SchedulerBase) GetSchedulerID() int32 { return sb.id } func (k *Ke...
package timingwheel import ( "context" "sync" "sync/atomic" "time" "unsafe" ) // WithTimeout returns a context value with time.Now().Add(timeout) as deadline. // // If the provided timeout is greater than 80 seconds, or the parent context // already has deadline setup, this function simply calls // `context.With...
package zseek import ( "io" "io/ioutil" "os" "testing" ) func testSetup(t *testing.T) (z *ZSeek, cleanup func()) { f, err := ioutil.TempFile(os.TempDir(), "zseek") if err != nil { t.Skip("temp file creation failed: ", err) t.SkipNow() } z, err = New(f) if err != nil { t.Skip("New failed: ", err) t.S...
package dbops import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "log" "time" "video_server/api/defs" "video_server/api/utils" ) // 添加用户 func AddUserCredential(loginName string, pwd string) error { stmtIns, err := dbConn.Prepare("INSERT INTO users(login_name,pwd) VALUES(?,?)") if err != nil { ...
package calldiv import ( "syscall" "github.com/b-2019-apt-test/divider/pkg/div" ) var ( math = syscall.NewLazyDLL(mathDLLName) divProc = math.NewProc("Div") ) // Divider performs decimal division by calling external lib (math.dll). var Divider = divider{} type divider struct{} // Div divides a by b with ro...
package main import ( "context" "fmt" "os" "path" "time" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/improbable-eng/thanos/pkg/compact" "github.com/improbable-eng/thanos/pkg/compact/downsample" "github.com/improbable-eng/thanos/pkg/objstore/client" "github.com/improbable-eng/t...
/* A thin wrapper for the lmdb C library. These are low-level bindings for the C API. The C documentation should be used as a reference while developing (http://symas.com/mdb/doc/group__mdb.html). Errors The errors returned by the package API will with few exceptions be of type Errno or syscall.Errno. The only error...
package types // An Item represents an effective record crawled by Spider. type Item interface { Content() string }
// Package parser turns the source text into a sequence of blocks. package parser import ( "bytes" "github.com/bouncepaw/mycomarkup/v2/blocks" "github.com/bouncepaw/mycomarkup/v2/mycocontext" "sync" ) // Parse parses the Mycomarkup document in the given context. All parsed blocks are written to out. func Parse(ct...
package parametrs // http://ocrsdk.com/documentation/apireference/processBarcodeField/ type ProcessBarcodeField struct { IParamers Region string `tag_name:"region"` BarcodeType string `tag_name:"barcodeType"` ContainsBinaryData string `tag_name:"containsBinaryData"` Description string `t...
package drivestream import "github.com/scjalliance/drivestream/resource" // DriveMap is a map of drivestream drives. type DriveMap interface { // List returns a list of all drives within the map. List() (ids []resource.ID, err error) // Ref returns a drive reference. Ref(driveID resource.ID) DriveReference }
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main ...
// +build agrasta383 package agrasta import "fmt" // Number of rounds. const Rounds = 6 // Block size. const BlockSize = 383 const BlockWords = 6 // Total size (in 64bit words) of signle matrix triangle. // The series must go on up until BlockWords const LTSize = 64 + 64*2 + 64*3 + 64*4 + 64*5 + 64*6 func (r *Bloc...
package services // import ( // "errors" // "github.com/messagedb/messagedb/meta/bindings" // "github.com/messagedb/messagedb/meta/models" // "github.com/messagedb/messagedb/meta/schema" // log "github.com/Sirupsen/logrus" // "gopkg.in/mgo.v2" // ) // var ( // ErrTeamDuplicateKey = errors.New("...
package api import ( "github.com/gocarina/gocsv" "os" ) type Route struct { ID string `csv:"route_id"` Name string `csv:"route_short_name"` LongName string `csv:"route_long_name"` } type RouteReader struct { routes map[string]Route } func NewRouteReader() RouteReader { var routes = []Route{} var r...
package window import ( "time" "github.com/idiocracy/mrv/streams" ) // Window holds window state type Window struct { stream chan streams.Ticker size time.Duration state slidingWindow } // New creates a window aggregator. // Takes a Ticker channel and a window size as input func New(stream chan streams.Tick...
package apiserver import ( "io" "log" "net/http" "github.com/chlins/obs/pkg/register" ) // Start api server func Start(l string) { http.HandleFunc("/objects/", handle) register.Prepare() log.Fatal(http.ListenAndServe(l, nil)) } func handle(w http.ResponseWriter, r *http.Request) { // select one data server ...
package f3 import ( "bytes" "net/http" "time" ) // AccountsEndpoint allows sending POST, GET, DELETE requests const AccountsEndpoint = "/organisation/accounts" // HealthEndpoint allows sending GET requests const HealthEndpoint = "/health" // HTTPParams is map used for url paramaters type HTTPParams map[string]st...
package accounts import ( "fmt" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/coretypes/cbalances" "github.com/iotaledger/wasp/packages/kv" "github.com/iotaledger/wasp/packages/kv/codec" "github.com/i...
package humanize import ( "fmt" "go/ast" "go/parser" "go/token" "os" "path/filepath" "strings" ) // Import is one imported path type Import struct { Package string Canonical string Path string Docs Docs Folder string pkg *Package } func (i *Import) String() string { if i.Canonical != i.Pa...
package problem import ( "fmt" "time" ) type number struct { value int64 } func (c *number) Add(x int64) { c.value++ } func syncWithMutex() { counter := number{} for i := 0; i < 100; i++ { go func(no int) { for i := 0; i < 10000; i++ { counter.Add(1) } }(i) } time.Sleep(time.Second) fm...
package field_test import ( "bytes" "encoding/hex" "io" "reflect" "testing" "github.com/tombell/go-serato/serato/field" ) func TestNewField69Field(t *testing.T) { data, _ := hex.DecodeString("000000450000000400000000") buf := bytes.NewBuffer(data) hdr, err := field.NewHeader(buf) if err != nil { t.Fatal...
// 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 ...
// Copyright 2018 Andrew Bates // // 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 wri...
/* * Copyright 2018- The Pixie 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 ag...
package main import ( "fmt" "go/wordfilter/trie" "net/http" "stayreal/goini" "github.com/gorilla/mux" "github.com/urfave/negroni" log "common/log4go" ) type WordFilterServer struct { trie *trie.Trie listen string replace string } func NewWordFilterServer() *WordFilterServer { iniFile := goini.Init("...
package filecenter import ( "log" "moriaty.com/cia/cia-supporter/bean" "moriaty.com/cia/cia-supporter/dao" ) /** * @author 16计算机 Moriaty * @version 1.0 * @copyright :Moriaty 版权所有 © 2020 * @date 2020/4/7 14:25 * @Description TODO * 文件中心服务 dao */ // 存入文件 func InsertFile(file *bean.File) (int64, error) { sq...
/* 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, so...
package filemonitor import ( "crypto/tls" "crypto/x509" "sync" "github.com/fsnotify/fsnotify" "github.com/sirupsen/logrus" ) type certStore struct { mutex sync.RWMutex cert *tls.Certificate tlsCrtPath string tlsKeyPath string } // NewCertStore returns a store for storing the certificate data and...
package models import ( // "encoding/json" "errors" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" "time" ) type MyDate time.Time func (self MyDate) MarshalJSON() ([]byte, error) { t := time.Time(self) if y := t.Year(); y < 0 || y >= 10000 { if y < 2000 { return []byte(`"2000-01-01 0...
package main import ( "testing" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" ) const ( namespace = "default" taintNodeNotReadyName = "notReady" ) func setupMockKubernetes(t *testing.T, node *v1.Node, config *v1...
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func readdata(fname string) (lines []string) { f, err := os.Open(fname) if err != nil { log.Fatalf("Error opening dataset '%s': %s", fname, err) } defer f.Close() scanner := bufio.NewScanner(f) scanner.Split(bufio.ScanLines) for sc...
// 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 ...
// 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 fuse import ( "sync" "fmt" "unsafe" "log" ) var _ = log.Println // This implements a pool of buffers that returns slices with capacity // (2^e * PAGESIZE) for e=0,1,... which have possibly been used, and // may contain random contents. type BufferPool struct { lock sync.Mutex // For each exponent a l...
package mat import ( "math" "math/rand" ) func NewCone() *Cone { m1 := New4x4() //NewMat4x4(make([]float64, 16)) inv := New4x4() //NewMat4x4(make([]float64, 16)) return &Cone{ Id: rand.Int63(), Transform: m1, Inverse: inv, Material: NewDefaultMaterial(), MinY: math.Inf(-1), MaxY:...
package main import ( route3 "P-Learn-Go/001-Introduction/Rename/route" route2 "P-Learn-Go/001-Introduction/Rename/route" ) func main() { route2.Http() route3.Http() }
package main import "fmt" type Point struct { x int y int } type Rect struct { leftUp, rightDown Point } type Rect2 struct { leftUp, rightDown *Point } func (rect Rect) updateLeftUpX(n int) { rect.leftUp.x = n } func main() { r1 := Rect{Point{1,2}, Point{3, 4}} r1.updateLeftUpX(11); fmt.Println(r1) // r1...
package main import ( "errors" "math" "os" "github.com/jcorbin/anansi" "github.com/jcorbin/anansi/x/platform" ) type schotterDemoUI struct { *schotterDemo } func runInteractive() { platform.MustRun(os.Stdin, os.Stdout, func(p *platform.Platform) error { var ui schotterDemoUI ui.schotterDemo = &sd ui.sq...
package pv_monitor_controller import ( "testing" v1 "k8s.io/api/core/v1" "github.com/container-storage-interface/spec/lib/go/csi" "github.com/kubernetes-csi/external-health-monitor/pkg/mock" "github.com/kubernetes-csi/external-health-monitor/pkg/util" ) func Test_AbnormalVolumeWithoutNodeWatcher(t *testing.T) ...
package main var dx []int var dy []int // DFS的调用者 func solve(board [][]byte) { /* 1. 确定搜索方向dx、dy */ dx = []int{0, 0, -1, 1} dy = []int{1, -1, 0, 0} if len(board) == 0 { return } m, n := len(board), len(board[0]) /* 2. 对坐标进行DFS搜索 (这里开始调用DFS函数) */ for i := 0; i < m; i++ { DFS(board, i, 0) DFS(board, i,...
package main import "fmt" func main() { var n int fmt.Scanf("%d", &n) var min float64 for i := 0; i < n; i++ { var price, grams float64 fmt.Scanf("%f %f", &price, &grams) total := (1000.0 / grams) * price if total < min || i == 0 { min = total continue } } fmt.Printf("%.2f\n", min) }
package gourmet import ( "fmt" "os" "strconv" "testing" "github.com/joho/godotenv" "github.com/stretchr/testify/assert" ) func init() { _, err := os.Stat("../.env") if !os.IsNotExist(err) { _ = godotenv.Load("../.env") } } func TestQueryExec(t *testing.T) { // assert := assert.New(t) q := QueryParam{ ...