text
stringlengths
11
4.05M
package entity import ( "errors" "path/filepath" "strings" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/store" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/util" profileConfig "github.com/hyperledger/fabric/common/tools/configtxgen/localconfig" ) type Consortium struct { //Orde...
// Copyright 2017 The hzwy23 . All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // authorization management // Now this package did not use for the time being // all authorization handle is relation to resources. so you can find authorization ...
package main import ( "fmt" "io/ioutil" "log" "net/http" "strings" "github.com/perrito666/gobinstapler/prytool" ) /* MIT License Copyright (c) 2019 Horacio Duran <horacio.duran@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentatio...
package tools import ( "bufio" "fmt" "log" "os" ) var filename = "output_response.txt" //WriteFile used for write response to text func WriteFile(msg string) error { f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return err } defer f.Close() _, err = fmt.Fprintln(f, msg) ...
package service type LinkError string func (e LinkError) Error() string { return string(e) } const ( ErrLongLinkNotFound LinkError = "Long link not found, check correctness of short link" ErrCodeConflict LinkError = "Short link already exists" ErrInvalidCode LinkError = "Custom link must contain only alphanumeri...
package apitest import ( gk "github.com/onsi/ginkgo" ) var testServer *TestServer var _ = gk.BeforeSuite(func() { testServer = new(TestServer) testServer.Initialize() }) var _ = gk.AfterSuite(func() { //No Need to revert the App Mode. testServer.Shutdown() })
package models import ( u "businessense/utils" "github.com/jinzhu/gorm" ) //Solution Type type Solution struct { gorm.Model Name string `json:"name"` Description string `json:"description"` Implementation string `json:"implementation"` SkillsTools string `json:"skillstools"` } //Create Soluti...
package fakes import ( bmstemcell "github.com/cloudfoundry/bosh-micro-cli/stemcell" bmvm "github.com/cloudfoundry/bosh-micro-cli/vm" ) type CreateInput struct { StemcellCID bmstemcell.CID NetworksSpec map[string]interface{} CloudProperties map[string]interface{} Env map[string]interface{} } ...
package protocol // MakeCEKResponse creates CEKResponse instance with given params func MakeCEKResponse(responsePayload CEKResponsePayload) CEKResponse { response := CEKResponse{ Version: "0.1.0", Response: responsePayload, } return response } func MakeCEKResponsePayload(msg string, ses bool) CEKResponsePayl...
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ag...
package open_im_sdk import ( "bytes" "crypto/md5" "encoding/gob" "encoding/hex" "encoding/json" "errors" "github.com/gorilla/websocket" "io" "io/ioutil" "net/http" "os" "path" sLog "log" "math/rand" "runtime" "strconv" "strings" "time" ) func operationIDGenerator() string { return strconv.Format...
package initializers import ( "github.com/wajox/gobase/internal/app/build" ) // InitializeBuildInfo creates new build.Info func InitializeBuildInfo() *build.Info { return build.NewInfo() }
package hello import ( "fmt" ) func Sqrt(x float64) (float64, int) { closeEnough := true z := 1.0 i := 0 for closeEnough { zn := (z - ((z*z)-x)/(2*z)) fmt.Println(zn, z, (zn - z)) delta := zn - z if delta < 0 { delta *= -1 } if delta < 0.01 { closeEnough = false } z = zn i++ } return...
package main import ( "log" "github.com/bongnv/gokit/examples/hello/internal/handlers" "github.com/bongnv/gokit/examples/hello/internal/service" gokitServer "github.com/bongnv/gokit/util/server" ) func main() { opts := []gokitServer.Option{ gokitServer.WithHTTPAddress(":8080"), } opts = append(opts, service...
// 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://aws.amazon.com/apache2.0/ // // or in the "license" file acco...
package gotest import ( "database/sql" "flag" "fmt" "math/rand" "runtime" "sort" "strconv" "strings" "testing" "github.com/google/btree" _ "github.com/mattn/go-sqlite3" ) func BenchmarkSqlite(b *testing.B) { db, err := sql.Open("sqlite3", ":memory:") if err != nil { b.Fatal(err) } defer db.Close() ...
package main func isUgly(num int) bool { if num <= 0 { return false } factors := []int{2, 3, 5} for _, v := range factors { for num%v == 0 { num /= v } } if num == 1 { return true } return false }
package main import ( "encoding/binary" "io" "log" "net" ) func handler(conn *net.TCPConn, csId, maxConn string) { wg.Add(1) in := make(chan []byte, 1024) out := make(chan []byte, 1024) cs := NewCs(csId, maxConn, out) defer func() { close(in) cs.closeOut() conn.Close() wg.Done() }() go msgIn(cs, in...
package utils import ( "errors" "fmt" "math" "strings" ) const ( /* base62Range is the possible different characters in short url unique identifier let's say our short url is: https://www.localhost:8080/ab53hRdpZhf then ab53hRdpZhf is the unique identifier */ base62Range = "abcdefghijklmnopqrstuvwxyzABCD...
package cache import ( "bytes" //"reflect" //"time" "math/rand" "os" "testing" ) func TestFSFindApproximateOldFiles(t *testing.T) { f, err := NewFS(func(f *FS) { f.Quota = 100; f.Basepath = "./testdata/gc-test/" }) if err != nil { t.Fatalf("Error creating FS: %s", err) } os.RemoveAll(f.Basepath) // Make s...
package proxy import ( "context" "fmt" "net/http" "os" "os/signal" "sync/atomic" "syscall" "time" "github.com/electroprovodka/loadbalancer/config" log "github.com/sirupsen/logrus" ) type ProxyServer struct { server *http.Server router *http.ServeMux proxy *Proxy // healthy is the marker of the server ...
// server_test.go package main import ( sdz "github.com/mzimmerman/sdzpinochle" pt "github.com/remogatto/prettytest" "sort" "strconv" "testing" ) func TestFoo(t *testing.T) { pt.RunWithFormatter( t, new(pt.TDDFormatter), new(testSuite), ) } func C(c string) sdz.Card { return sdz.Card(c) } type testSui...
package clcv2 /* * Routines to specify/parse CIDR strings */ import ( "fmt" "net" "strings" "github.com/pkg/errors" ) // CIDRs implements the flag.Value interface, allowing to speciy multiple CIDR values. type CIDRs []string // String implements the flag.Value String method for CIDRs. func (c CIDRs) String() ...
package config import ( "encoding/json" "io/ioutil" ) type Configuration struct { Databases DatabasesConf `json:"Databases"` Api ApiConf `json:"Api` GCP GCPConf `json:"GCP"` } type GCPConf struct { BucketUsersFiles string `json:"BucketUsersFiles"` } type DatabasesConf struct { MongoDb MongodbCon...
package filesystem import ( "path/filepath" "github.com/pkg/errors" ) func (g *Got) UpdateIndex(filename string) error { filepath.Join(g.dir, filename) abs, err := filepath.Abs(filename) if err != nil { return err } rel, err := filepath.Rel(g.dir, abs) sum, err := g.HashFile(rel, false) if err != nil { ...
package resolver import ( "strconv" graphql "github.com/graph-gophers/graphql-go" ) type Resolver struct{} func (r *Resolver) GetUser(args struct{ ID graphql.ID }) (*UserResolver, error) { u, err := db.getUser(args.ID) if err != nil { return nil, err } return &UserResolver{u}, nil } func (r *Resolver) GetT...
package main import "fmt"; import "net"; import "io"; func main() { ln,err:=net.Listen("tcp",":3000") if err!=nil{ panic(err); } defer ln.Close() for{ conn,err := ln.Accept() fmt.Println("hello world") if err !=nil{ panic(err) } io.Copy(conn,conn) conn.Close() } }
package validate import ( "fmt" "net/url" "reflect" "testing" ) type TestCaseMessage struct { Form url.Values Errors []error } type TestCaseAddress struct { Address string Error error } // TestGenerateAPIKey ensures that generated api keys // match the specified format func TestAddress(t *testing.T) { ...
package endpoints import ( "context" "encoding/json" "fmt" "net/http" "time" "github.com/go-kit/kit/endpoint" kithttp "github.com/go-kit/kit/transport/http" "github.com/google/uuid" domain "github.com/sumelms/microservice-course/internal/matrix/domain" "github.com/sumelms/microservice-course/pkg/validator"...
package tracefs import ( "fmt" "os" "testing" qt "github.com/frankban/quicktest" ) // Global symbol, present on all tested kernels. const ksym = "vprintk" func TestKprobeTraceFSGroup(t *testing.T) { c := qt.New(t) // Expect <prefix>_<16 random hex chars>. g, err := RandomGroup("ebpftest") c.Assert(err, qt....
package sand import ( "encoding/json" "io" "io/ioutil" "log" "math/rand" "net/http" "os" "path" "time" "github.com/gorilla/mux" ) var userCurrentSession map[string]string func init() { rand.Seed(time.Now().UnixNano()) userCurrentSession = make(map[string]string) } var letterRunes = []rune("abcdefghijkl...
package rtda type Frame struct { lower *Frame localVars LocalVars operandStack *OperandStack } func newFrame(maxLocals,maxStack uint) *Frame { return &Frame{ localVars:newLovalVars(maxLocals), operandStack:newOperandStack(maxLocals), } }
package srv import ( "errors" "fmt" "github.com/dgrijalva/jwt-go" "github.com/golang/glog" "qipai/dao" "qipai/enum" "qipai/model" "qipai/utils" "time" ) var User userSrv func initUser() { User.j = utils.NewJWT() } type userSrv struct { j *utils.JWT } func (userSrv) Register(user *model.User) (err error)...
package jsondiff import ( "testing" "github.com/stretchr/testify/assert" ) func TestDiffDifferent(t *testing.T) { mapA := map[string]interface{}{ "fieldA": 12, "fieldB": "foo", "fieldC": 34.55, "fieldD": 11.22, "fieldE": "baz", "fieldZ": "foobar", "fieldArray1": []int{1, 2, 3, 4, 5}, "fieldArray2...
package UserRepository import ( "MainApplication/internal/User/UserModel" "errors" ) var EmailAlreadyExists = errors.New("Email already exist!") var DbError = errors.New("Data Base error!") var CantAddSession = errors.New("Add session error!") var CantAddUser = errors.New("Add user error!") var CantGetUserByEmail =...
package main import ( "github.com/solrac97gr/cryptoAPI/api" cacheDb "github.com/solrac97gr/cryptoAPI/cache" "github.com/solrac97gr/cryptoAPI/database" ) func main() { cacheDb.InitCache() database.InitFirebase() api.Init() }
package nats import "regexp" var supportedCharacters = regexp.MustCompile("[^a-zA-Z0-9-_]+") func GetClientID(value string) string { return supportedCharacters.ReplaceAllString(value, "_") }
package vo type MatchINFVO struct { //比赛ID Id int64 `json:"id"` //暂时不明白其意义 tr中可获取 Selects []int `json:"selects"` //所选择的赔率 Values []float64 `json:"values"` } /** 发布推荐 */ type PubVO struct { //标题15字 Title string `json:"title"` //内容100字 Content string `json:"content"` //收费价格 Price int64 `json:"price"` Mu...
package message import ( "fmt" "github.com/gin-gonic/gin" message "../../service/message_service" ) // Controller is message controlller type Controller struct{} // Index action: GET /messages func (pc Controller) Index(c *gin.Context) { var s message.Service userID, err1 := c.GetQuery("user_id") // クエリパラメー...
package main func maximalSquare(matrix [][]byte) int { res := 0 m := len(matrix) if m < 1 { return res } n := len(matrix[0]) dp := make([][]int, m) for i := 0; i < m; i++ { dp[i] = make([]int, n) for j := 0; j < n; j++ { if matrix[i][j] == '0' { continue } else if i == 0 || j == 0 { dp[i][j]...
// Sample program to show how to use an unbuffered channel to simulate a game of // tennis between two goroutines. package main import ( "fmt" "math/rand" "sync" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } func main() { // Create a unbuffered channel. court := make(chan int) // wg is used to m...
package docker import ( "io/ioutil" "log" "net/http" "regexp" "strings" "time" ) func GetCreateTime(dockerRegistry string, image string, tag string, user string, pass string) (string, error) { httpClient := &http.Client{} url := "https://" + dockerRegistry + "/v2/" + image + "/manifests/" + tag req, err := h...
package main import "fmt" func main() { //*******Slices********* // slice1 := []int{3, 5, 2, 1, 4} // fmt.Println(slice1) // // slice2 := slice1[2:] // slice2 := make([]int, 5, 10) // copy(slice2, slice1) // // slice2 = append(slice2, 0, 1) // fmt.Println(slice2) //*******functions********* listNum := [...
// https://github.com/wumansgy/goEncrypt // https://github.com/thinkoner/openssl package crypto import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/des" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "io" "math/big" "windzhu0514/go-utils/crypto/ecbcipher" ) const ( ModeECB = 1 << iot...
package main import ( log "github.com/Sirupsen/logrus" "github.com/gin-gonic/gin" "os" ) var Router *gin.Engine func main() { // Режим работы gin - на продакшене делать "ReleaseMode" gin.SetMode(gin.DebugMode) // Роутер по-умолчанию Router = gin.New() // Загрузить шаблоны Router.LoadHTMLGlob("templates/...
package main import ( "fmt" "net/http" ) //Creating the handler functions //w will assemble the server's response, and write it to the client; r will hold the client's request //Fprintf(w, "some_string") will write to the client screen func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello ...
package tenant import ( "fmt" "github.com/stretchr/testify/require" "strings" "testing" ) func Test_Env_Setup(t *testing.T) { runOnlyInIntegrationTest("TEST_OVH") brokerd_launched, err := isBrokerdLaunched() if !brokerd_launched { fmt.Println("This requires that you launch brokerd in background and set the ...
package presence import ( "fmt" "os" "strconv" "testing" "time" ) var nextID chan string var testTimeoutDuration = time.Second * 1 func init() { nextID = make(chan string) go func() { id := 0 for { id++ nextID <- "id" + strconv.Itoa(id) } }() } func initPresence() (*Session, error) { connStr :=...
package main import ( "flag" "fmt" "net/http" ) var addr string func init() { flag.StringVar(&addr, "http", ":4000", "address or port to bind to") flag.Parse() } func main() { r := router() http.Handle("/", r) fmt.Printf("Listening on %s\n", addr) http.ListenAndServe(addr, nil) } //
package g2gin import ( "bytes" "fmt" "io" "net/http" _ "net/http/pprof" //pprof "strings" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/spf13/cast" "github.com/atcharles/gof/v2/g2util" "github.com/atcharles/gof/v2/j2rpc" ) // G2gin ... type G2gin struct { Config *g2util....
package ssvgc_test import ( "strings" "testing" "github.com/llgcode/draw2d/draw2dimg" "github.com/stephenwithav/ssvgc" ) func TestSVGDrawing(t *testing.T) { if testing.Short() { t.Skip("Skipping lengthier tests during short test run.") } var rectangleDefinitions = []StringMap{ { "name": "solidblue",...
package main //Creating custom functions in Go import "fmt" func main() { greetings("Dan") greet0 := strGreetings("Huginn") fmt.Println(greet0) greet1, status := greetUser("Bullwinkle", "Thorwaldson") fmt.Println(greet1, status) } //Simple function func greetings(name string) { fmt.Println("Hello,", name) } ...
package main //记忆化搜索 //memo[i][c] 使用索引为[0...i]的元素是否可以填充容量为c的背包 func canPartition(nums []int) bool { n := len(nums) sum := 0 for i := 0; i < n; i++ { sum += nums[i] } if sum%2 != 0 { return false } memo := make([][]int, 0) for i := 0; i < n; i++ { tmp := make([]int, sum/2+1) for i := 0; i < sum/2+1; i++...
package main import "github.com/urfave/cli/v2" const ( flagAborted = "aborted" flagAnyPhase = "any-phase" flagBrowse = "browse" flagCanceled = "canceled" flagClient = "client" flagContainer = "container" flagContinue = "continue" flagCreate = "create" fla...
package main import "fmt" func main() { type noKtp = string type married = bool var noKtpEko noKtp = "317" fmt.Println(noKtpEko) var marriedStatus married = true fmt.Println(marriedStatus) }
package server import ( "database/sql" "encoding/json" "fmt" "log" "net/http" "strconv" "time" "github.com/jmoiron/sqlx" ) type dict map[string]interface{} type user struct { ID int64 `db:"id"` Email string `db:"email"` Password string `db:"password"` OID string `db:"oid"` SID int64...
package _561_Array_Partition import "sort" func arrayPairSum(nums []int) int { return arrayPairSumWithSort(nums) } func arrayPairSumWithSort(nums []int) int { sort.Ints(nums) x := 0 for i := 0; i < len(nums); i += 2 { x += nums[i] } return x }
package day08 import ( "strings" "testing" "github.com/stretchr/testify/require" ) func TestParseInstructions(t *testing.T) { tests := map[string]Instruction{ "nop +0": {Opcode: OP_NOP, Operand: 0}, "acc +1": {Opcode: OP_ACC, Operand: 1}, "jmp +4": {Opcode: OP_JMP, Operand: 4}, "acc +3": {Opcode: OP_...
package agrasta import "fmt" import "math/bits" import "encoding/binary" import "golang.org/x/crypto/sha3" type Block [BlockWords]uint64 type Matrix [BlockSize]Block type State struct { rbuf [17]uint64 rpos int sha3.ShakeHash } // LU algorithm: We generate only the lower half of LU decomposition. // Then, we str...
package main import "log" import "net/http" import "code.google.com/p/go.net/websocket" import "greyhound" var gs = greyhound.NewGreyhoundSearch() // a list of regex exclusions from the workspace var baseExclusions = []string{ ".*\\.class", ".*\\.pyc", "\\.keep", ".*\\.key", "\\.rspec", } func handleQuery(w h...
package lsof import ( "net" "os" "testing" "github.com/stretchr/testify/assert" ) func TestLoadSockets(t *testing.T) { go func() { conn, err := net.Dial("tcp", ":3000") if err != nil { t.Fatal(err) } defer conn.Close() }() l, err := net.Listen("tcp", ":3000") conn, err := l.Accept() if err != nil...
package nmea import ( "fmt" "time" ) // FixQuality represents the quality of a position fix in a GGA packet. type FixQuality int // FixQuality values const ( InvalidFix FixQuality = iota GPSFix DGPSFix PPSFix RealTimeKinematicFix FloatRealTimeKinematicFix EstimatedFix ManualInputModeFix SimulationModeFix ...
package fakes import "github.com/cloudfoundry-incubator/notifications/models" type Finder struct { Clients map[string]models.Client Kinds map[string]models.Kind ClientAndKindError error } func NewFinder() *Finder { return &Finder{ Clients: make(map[string]models.Client...
package controllers import ( gormc "github.com/revel/modules/orm/gorm/app/controllers" "github.com/revel/revel" "my-revel-modules/admin/app/models" ) type DoveaAdminApp struct { gormc.TxnController } func (c DoveaAdminApp) DbAutoMigrate() { } func (c DoveaAdminApp) Index() revel.Result { //c.Txn.LogMode(true)...
package mysqldb import ( "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" context "golang.org/x/net/context" ) // generateLocalNotification 生成随机测试用例 func generateLocalNotification() *LocalNotification { now := time.Now() return &LocalNotification{ Ti...
// Package pow provides a proof of work-based rate limiter. // // The design of this algorithm is described in detail here: // https://www.notion.so/covidwatch/Proof-of-Work-Design-1a17cfed3ff74092996c5c4373be71c6 package pow import ( "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" "time" "gola...
package api import ( db "github.com/dnswd/kanal/db/sqlc" "github.com/dnswd/kanal/util" "github.com/gofiber/fiber/v2" ) type Driver struct { config util.Config router *fiber.App store db.Store } func InitDriver(config util.Config, store db.Store) *Driver { driver := &Driver{ config: config, store: store, ...
package goutils import ( "fmt" "runtime/debug" "os" "log" "net/http" "encoding/json" "html/template" ) func CheckFatalErr(err error, msg string) { if err != nil { fmt.Fprintf(os.Stderr, msg) os.Exit(1) } } // Send a 400 - BadRequest error back to client func Send400Json(w http.ResponseWrite...
package golang func getMaxLen(nums []int) int { prevZeroIdx := -1 longest, length := 0, len(nums) negNumIdxRecord := make([]int, 0) for i := 0; i < length; i++ { if nums[i] == 0 { longest = max( longest, calcMaxLength(negNumIdxRecord, prevZeroIdx, i), ) prevZeroIdx = i negNumIdxRecord = neg...
package main import ( gServer "api/server" "api/talk_cloud" cfgGs "configs/grpc_server" "flag" "google.golang.org/grpc" "log" "net" "net/http" _ "net/http/pprof" ) func init() { // 加载数据库中所有的数据到缓存 //server.DataInit() //server.ConcurrentEngine{ // Scheduler: &server.SimpleScheduler{}, // WorkerCount: 10, ...
package boshio_test import ( "github.com/concourse/bosh-io-stemcell-resource/boshio" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Stemcells", func() { Describe("Details", func() { It("returns regular stemcell metadata", func() { stemcell := boshio.Stemcell{ Regular: &boshio....
package main import ( "github.com/veandco/go-sdl2/img" "github.com/veandco/go-sdl2/sdl" ) const ( CursorNormal = "normal" CursorResizeCorner = "resizecorner" CursorResizeCornerFlipped = "resizecorner_flipped" CursorResizeHorizontal = "resizehorizontal" CursorResizeVertical = "resize...
package Problem0135 func candy(ratings []int) int { n := len(ratings) if n <= 1 { return n } // left == big than left left := make([]int, n) // right == big than right right := make([]int, n) left[0] = 1 right[n-1] = 1 for i := 1; i < n; i++ { if ratings[i-1] < ratings[i] { // i 比左边的大 // 所以,他的数量要...
package main import "fmt" func main() { var numCols, maxCount int count := 1 fmt.Scanf("%d %d", &numCols, &maxCount) for count <= maxCount { for i := 0; i < numCols; i++ { fmt.Printf("%d", count) count++ if i < numCols-1 { fmt.Printf(" ") } } fmt.Printf("\n") } }
package bolt import ( "bytes" "os" "path/filepath" "sync" "time" "github.com/gotoolkit/store" bolt "go.etcd.io/bbolt" ) const ( dbFilePerm os.FileMode = 0644 defaultTimeout = time.Duration(10) * time.Second defaultBucket = "default" ) type Store struct { db *bolt.DB bucket []byte sync.Mutex } fu...
package inmemory import ( "strconv" "time" "github.com/Tanibox/tania-core/src/tasks/query" "github.com/Tanibox/tania-core/src/tasks/storage" "github.com/gofrs/uuid" ) type TaskReadQueryInMemory struct { Storage *storage.TaskReadStorage } func NewTaskReadQueryInMemory(s *storage.TaskReadStorage) query.TaskRead...
package servers import ( "net/http" "net/http/httptest" "sync" ) // Generic holds a generic web server that you can use to run your tests against type Generic interface { // Server is the running server. Don't forget to close this! Server() *httptest.Server // Requests gets the requests that have been sent to t...
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00100102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.001.001.02 Document"` Message *RedemptionBulkOrderV02 `xml:"setr.001.001.02"` } func (d *Document00100102) AddMe...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-07-21 12:22 * Description: *****************************************************************/ package xthrift import ( "context" "fmt" "github.com/...
/* Copyright 2020 Humio https://humio.com 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, ...
package main import ( "fmt" "log" "os" "time" "github.com/gomodule/redigo/redis" ) // NewPool returns a new pool to draw redis connections from func NewPool() *redis.Pool { rp := &redis.Pool{} rp.MaxIdle = 3 rp.IdleTimeout = 240 * time.Second rp.Dial = func() (redis.Conn, error) { redisServer := fmt.Sprin...
// Slice using array /* For creating a slice from the given array first you need to specify the lower and upper bound, which means slice can take elements from the array starting from the lower bound to the upper bound. It does not include the elements above from the upper bound. */ package main import "f...
package slacktest import ( "fmt" ) // ErrEmptyServerToHub is the error when attempting an empty server address to the hub var ErrEmptyServerToHub = fmt.Errorf("Unable to add an empty server address to hub") // ErrPassedEmptyServerAddr is the error when being passed an empty server address var ErrPassedEmptyServerAd...
package field import "github.com/graphql-go/graphql" func friends(p graphql.ResolveParams) (interface{}, error) { return []string{}, nil } // Friends returns a empty list. var Friends = graphql.Field{ Type: &graphql.List{ OfType: graphql.String, }, Resolve: friends, Description: "Get all friends.", }
package main import ( "flag" "log" "github.com/CristalT/gochat/client" "github.com/CristalT/gochat/tui" ) func main() { address := flag.String("server", "", "Server address") flag.Parse() client := client.NewClient() err := client.Dial(*address) if err != nil { log.Fatal(err) } defer client.Close() ...
/* 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...
/* * Copyright (c) 2020 - present Kurtosis Technologies LLC. * All Rights Reserved. */ package services import ( "fmt" "github.com/kurtosis-tech/kurtosis-go/lib/services" "github.com/sirupsen/logrus" "net/http" "time" ) type ExampleAvailabilityCheckerCore struct{} func (e ExampleAvailabilityCheckerCore) IsS...
// Copyright 2019 The Dice Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by app...
package main import ( "fmt" "net" "time" ) /* 模拟客户端 */ func main(){ fmt.Println("client start ...") time.Sleep(1* time.Second) // 1 直接连接远程服务器 得到 conn pConn,err := net.Dial("tcp","127.0.0.1:8999") if err != nil { fmt.Println("client start err:",err) return } // 2 连接调用 write 写数据 for { _,err := pConn...
package main /* * @lc app=leetcode id=239 lang=golang * * [239] Sliding Window Maximum */ // 关键是存放下标 func maxSlidingWindow(nums []int, k int) []int { var res []int deque := make(Deque239, 0) for i, num := range nums { if !deque.isEmpty() && deque.peekFirst() <= i-k { deque.pollFirst() } for !deque.isEm...
package types import ( "errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "math/big" "strings" "time" "github.com/ethereum/go-ethereum/common" "golang.org/x/crypto/sha3" ) const ( ADDRESS_LENGTH = 42 BYTES32_LENGTH = 66 ) type Direction uint8 const ( Long Direction = 0 Short Direction = 1 )...
package mail import ( "testing" "path/filepath" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // MailTestSuite 是邮件发送的测试suite type MailTestSuite struct { suite.Suite client *Client } func (suite *MailTestSuite) SetupSuite() { options, _ := newMailOptionfromEnvFile(filepath.Join("...
package main import "fmt" func square_sum(from int, to int) int { sum := 0 for i := from; i <= to; i++ { sum += i } return sum * sum } func sum_squares(from int, to int) int { sum := 0 for i := from; i <= to; i++ { sum += i * i } return sum } // Sum square difference func main() { fmt.Println(squar...
package objs import "time" const ( UnreadMessage = 1 InfoMessage = 1 << iota WarningMessage DangerMessage ) type Message struct { MessageId int `json:"message_id"` Date time.Time `json:"date"` Status int `json:"status"` ReceiverId int `json:"receiver_id"` SenderId int `json:"sender_id"` Pri...
package main import ( "bufio" "encoding/json" "fmt" "math/big" "net" "os" "time" ) type message struct { Fib *big.Int Time time.Duration } func main() { go Input() ListeningFromServer() } func Input() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { go SendToServer("127.0.0.1:1337", sca...
func wordBreak(s string, wordDict []string) bool { d := make(map[string]bool) for _, s := range wordDict { d[s] = true } m := make(map[string]bool) return b(s, d, m) } func b(s string, d map[string]bool, m map[string]bool) bool { if res, ok := m[s]; ok { return res } for...
package builder import ( "context" "errors" "fmt" "io" "log" "net/http" "os" "strings" "time" "cloud.google.com/go/compute/metadata" "github.com/masterzen/winrm" "github.com/packer-community/winrmcp/winrmcp" ) const ( runTimeoutDef = 5 ) // Remote represents a remote Windows server. type Remote struct ...
package main import ( "bufio" "crypto/hmac" "crypto/sha1" "crypto/tls" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "net/http" "os" "regexp" "strings" "github.com/google/go-github/github" ) // type Check struct { // Team *string `json:"team,omitempty"` // Pipeline *string `json:"pipeline...
package main func sensorDisconnect(deviceid string) { sensorAlive(deviceid, "", "", true, 0, 0) }
package main import ( "testing" ftypes "github.com/openfaas/faas-provider/types" ) func Test_makeFunctionURL_DefaultPathQS_IncludesGWAddress(t *testing.T) { config := QueueWorkerConfig{ FunctionSuffix: "", GatewayAddress: "gateway", GatewayPort: 8080, } req := ftypes.QueueRequest{ Function: "function...