text
stringlengths
11
4.05M
package smallNet type NetworkConfig struct { Network string // tcp4(ipv4 only), tcp6(ipv6 only), tcp(ipv4, ipv6) BindAddress string // 만약 IP와 포트번호 결합이면 localhost:19999 MaxSessionCount int // 최대 클라이언트 세션 수. 넉넉하게 많이 해도 괜찮다 MaxPacketSize int // 최대 패킷 크기 RecvPacketRingBufferM...
package main import ( "fmt" "os" "github.com/Cloud-Foundations/Dominator/lib/filesystem" "github.com/Cloud-Foundations/Dominator/lib/filter" "github.com/Cloud-Foundations/Dominator/lib/log" ) func showImageInodeSubcommand(args []string, logger log.DebugLogger) error { if err := showImageInode(args[0], args[1])...
package receiver import ( "github.com/btcsuite/btcd/chaincfg" ) type policy struct { SoftTimeout int FundingMinConf int } var policies = map[string]policy{ "mainnet": policy{ SoftTimeout: 144, FundingMinConf: 3, }, "testnet3": policy{ SoftTimeout: 32, FundingMinConf: 1, }, } func getPolicy(n...
/* Go Language Raspberry Pi Interface (c) Copyright David Thorpe 2016-2018 All Rights Reserved Documentation http://djthorpe.github.io/gopi/ For Licensing and Usage information, please see LICENSE.md */ // Interacts with the BME280 sensor package main import ( "errors" "fmt" "os" // Frameworks "g...
package goSolution import "testing" func TestSolveNQueens(t *testing.T) { answer := [][]string{{".Q..","...Q","Q...","..Q."},{"..Q.","Q...","...Q",".Q.."}} AssertEqual(t, answer, solveNQueens(4)) }
/* * @lc app=leetcode.cn id=134 lang=golang * * [134] 加油站 */ // @lc code=start package main import "fmt" import "math" func main() { var gas, cost []int gas = []int{1,2,3,4,5} cost = []int{3,4,5,1,2} fmt.Println(canCompleteCircuit(gas, cost)) gas = []int{2,3,4} cost = []int{3,4,3} fmt.Println(canCompl...
package flash import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestNew(t *testing.T) { Convey("Given new flash", t, func() { f := New() Convey("Flash should not be nil", func() { So(f, ShouldNotBeNil) }) Convey("Flash data should be empty", func() { So(f.v, ShouldBeEmpty) }...
package main import ( "bytes" "crypto/tls" b64 "encoding/base64" "fmt" "github.com/elazarl/go-bindata-assetfs" "github.com/gerald1248/timeline" "github.com/kabukky/httpscerts" "io/ioutil" "log" "net/http" "time" ) type PostStruct struct { Buffer string } func serve(certificate, key, hostname string, port...
// 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 middleware import ( "net/http" "strings" "github.com/clivern/walrus/core/driver" "github.com/clivern/walrus/core/model" "github.com/clivern/walrus/core/util...
package leetcode /*We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.) A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Return a list of all uncommon words. You may ret...
package virtual_security import ( "errors" "log" "reflect" "testing" "time" ) type testStockService struct { iStockService newOrderCode1 []string newOrderCodeCount int confirmContract1 error confirmContractCount int getStockOrders1 ...
package main import ( "crypto" "crypto/rsa" "fmt" "io" "io/ioutil" "log" "golang.org/x/crypto/ssh" ) type keychain struct { key *rsa.PrivateKey } func (k *keychain) Key(i int) (ssh.PublicKey, error) { if i != 0 { return nil, nil } return ssh.NewPublicKey(&k.key.PublicKey) } func (k *keychain) Sign(i i...
package proto import ( "cm_liveme_im/libs/bufio" "cm_liveme_im/libs/bytepool" "cm_liveme_im/libs/bytes" "cm_liveme_im/libs/define" "encoding/binary" "errors" "fmt" log "github.com/thinkboy/log4go" "time" ) const ( // required header size SizePackLen = 4 SizeHdrLen = 2 SizeVer = 2 SizeOpCode ...
package dao import ( "errors" "git.dustess.com/mk-base/util/crypto" "git.dustess.com/mk-training/mk-blog-svc/pkg/tags/model" "go.mongodb.org/mongo-driver/bson" ) // InsertTags 插入标签数据 func (m *TagDao) InsertTags(data []string) ([]string, error) { if len(data) == 0 { return nil, errors.New("tags is empty") } v...
package guessit import ( "encoding/json" "net/http" "net/url" ) const ( BASE_URL = "http://guessit.io/" ) type GuessResult struct { AudioChannels string `json:"audioChannels"` AudioCodec string `json:"audioCodec"` Container string `json:"container"` EpisodeNumber int64 `json:"episodeNumber"` Format ...
package config import ( ) type Config struct { DockerURL string TLSCACert string TLSCert string TLSKey string ActiveActiveSrvcsCnslPath string BuddyCluster string RemoteGateWayCnslPath string AllowInsecure bool PollInterval string ConsulHost string ConsulPort int ConsulTemplate string DefaultHealthChkUR...
package datacenter import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" "github.com/sanguohot/medichain/etc" "github.com/sanguohot/medichain/util" "github.com/sanguohot/medichain/zap" "io/ioutil" "os" ) type FileAddLog struct { FileUuid string OwnerUuid string UploaderUuid string OrgUuid string F...
package router import ( "project/app/admin/apis" "project/app/admin/middleware" "strconv" "github.com/gin-gonic/gin" ) func init() { // 无需认证接口 //routerNoCheckRole = append(routerNoCheckRole, roleAuthRouter) // 认证 routerCheckRole = append(routerCheckRole, roleAuthRouter) } func roleAuthRouter(v1 *gin.RouterG...
package main import( "fmt" "time" "math/rand" ) var a[25]int var x[25]int var t int func main() { x =[25]int{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25} for k :=0;k<=24;k++{ a[k]=rand.Intn(105)+15 } for i :=0;i<8;i++ { go cafe(i) } time.Sleep(time.Millisecond) for v :=8;v<25;...
/* Copyright 2019 Dmitry Kolesnikov, 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 l...
package torrentapi import ( "errors" "fmt" "reflect" "strings" "testing" "time" ) func TestTokenIsValid(t *testing.T) { testData := []struct { desc string token Token want bool }{ { desc: "Valid Token", token: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}, want: true, ...
package gotappd // Interface for parameter objects type parameter interface { // Get the parameters formatter as url parameters urlformat() string } // Parameters for querying user information type UserInfoParams struct { // compact (string, optional) - You can pass "true" here only show the user information, /...
package main import ( "bufio" "encoding/json" "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" "sort" "strings" "sync" "time" ) var ( sourceURLValidatorMap = map[string]lineValidator{ `https://raw.githubusercontent.com/notracking/hosts-blocklists/master/hostnames.txt`: hostLine("0.0.0.0")...
package main import ( "flag" "fmt" "os" "path" "strings" utils "github.com/yametech/cloud-native-tools/pkg/utils" ) func main() { var url, codeType, projectPath, command string var unitTest, sonar bool flag.StringVar(&url, "url", "./Dockerfile", "-url ./") flag.StringVar(&codeType, "codetype", "java-maven...
package parser_test import ( "encoding/json" "fmt" "io/ioutil" "testing" "github.com/bddbnet/gospy/engine" "github.com/bddbnet/gospy/model" "github.com/bddbnet/gospy/parser/h.bilibili.com" ) // step 4 获取用户图片总数 func TestUserUploadCount(t *testing.T) { bytes, err := ioutil.ReadFile("count.json") if err != nil...
// Package jobcontroller is the main Job runner for peridot. // It operates as a set of gRPC clients, with each Agent separately // running its own gRPC server. // SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later package jobcontroller import ( "context" "fmt" "log" "sync" "github.com/swinslow/peridot-core...
package main import ( "time" "strconv" _ "net/http/pprof" "net/http" "log" "fmt" "os" "io/ioutil" "runtime/debug" "io" ) type Item int64 type Holder struct { objects map[string]*Item } func (h *Holder) survive(dur time.Duration) { time.Sleep(dur) } func main() { h1 := Holder{ objects: make(map[string...
package main import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCatJSON(t *testing.T) { tests := []struct { name string b []byte want Cat }{ { b: []byte(`{"name":"Cheshire"}`), want: Cat{Animal: &Animal{Name: "Cheshire"}}...
package process import ( "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "io/ioutil" "net/http" "nginx-manager/utils" "os" ) type ResponseInfo struct { Status int Message string Data interface{} } const nginxHttpDir = "/opt/nginx/conf/conf.d/" const nginxBinaryFile = "/opt/nginx/sbin/nginx" fun...
package grade import ( md "github.com/ebikode/eLearning-core/model" tr "github.com/ebikode/eLearning-core/translation" ) // GradeService provides grade operations type GradeService interface { GetGradeReports(int, int) []*md.GradeReport GetGrade(uint) *md.Grade GetGrades(int, int) []*md.Grade GetGradesByApplica...
package task import ( "github.com/robfig/cron" ) func PrepareCron() { spec := "0, 10, 1, *, *, *" // 每天6:40 c := cron.New() c.AddFunc(spec, taskEveryDay()) c.Start() }
package parser import ( "regexp" ) func tokenize(sexpr string) []string { re := regexp.MustCompile(`[\s,]*(~@|[\[\]{}()'` + "`" + `~^@]|"(?:\\.|[^\\"])*"?|;.*|[^\s\[\]{}('"` + "`" + `,;)]*)`) rawTokens := []string{} for _, group := range re.FindAllStringSubmatch(sexpr, -1) { if (group[1] == "") || (group[1]...
package pgsql import ( "testing" ) func TestPath(t *testing.T) { testlist2{{ valuer: PathFromFloat64Array2Slice, scanner: PathToFloat64Array2Slice, data: []testdata{ {input: [][2]float64(nil), output: [][2]float64(nil)}, { input: [][2]float64{{0, 0}}, output: [][2]float64{{0, 0}}}, { in...
package main import ( "io/ioutil" "net/http" "regexp" ) func main(){ url := "https://github.com/probloys/webCatchForGit/file-list/master" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("cache-control", "no-cache") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := ioutil.Re...
package utils import "testing" func BenchmarkSlice2String(b *testing.B) { info := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} for i := 0; i < b.N; i++ { _, _ = Slice2String(info) } } func TestSlice2String(t *testing.T) { info := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} result := "1,2,3,4,5,6,7,8,9" str, _ := Slice2String(info)...
// Written in 2014 by Petar Maymounkov. // // It helps future understanding of past knowledge to save // this notice, so peers of other times and backgrounds can // see history clearly. package model import ( "github.com/hoijui/escher/pkg/be" cir "github.com/hoijui/escher/pkg/circuit" "github.com/hoijui/escher/pkg...
package helpers import ( "golang.org/x/crypto/bcrypt" ) //HashPassword from string func HashPassword(pwd string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(pwd), 10) return string(bytes), err } //CheckPasswordHash compares regular password to hashpassword. Returns true in success or false ...
package connect import ( "context" "database/sql" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/lifenglin/micro-library/helper" "github.com/sirupsen/logrus" mysql2 "gorm.io/driver/mysql" gorm2 "gorm.io/gorm" "gorm.io/plugin/prometheus" "path/filepath" "sync" "time" )...
package pas import ( "fmt" "github.com/galaco/bsp/lumps" "log" ) func Calculate(numPortalClusters int) { var bitbyte int32 var dest, src *int64 var scan *byte var uncompressed [lumps.MAX_MAP_LEAFS/8]byte var compressed [lumps.MAX_MAP_LEAFS/8]byte fmt.Printf("Building PAS...\n") count := 0 for i := 0; i <...
package dbl import ( "database/sql" "fmt" "net" "net/http" "net/http/httputil" //"path" "github.com/dustin/go-humanize" "github.com/espebra/filebin2/ds" "strconv" "time" //"github.com/gorilla/mux" ) type TransactionDao struct { db *sql.DB } func (d *TransactionDao) Register(r *http.Request, bin string, f...
package paramedic const Version = "0.1.6"
package main import "fmt" /* @Time : 2020/8/12 15:27 @Author : DELL ricemarch@foxmail.com @tips: https://leetcode-cn.com/problems/merge-sorted-array/ */ func merge(nums1 []int, m int, nums2 []int, n int) { max := m + n left, right := m-1, n-1 i := 1 for left >= 0 && right >= 0 { if nums1[left] < nums2[right] {...
/* * Copyright 2018 Haines Chan * * This program is free software; you can redistribute and/or modify it * under the terms of the standard MIT license. See LICENSE for more details */ package runtime // Runtime is the interface for runtime of the CNI type Runtime interface { }
package library //file scope import "fmt" //package scope var gopher = "gopher!!" func bye() { //block scope var msg = "bye bye" fmt.Println("from library hello.go:", msg, gopher) }
package gag9 import ( "bytes" "reflect" "testing" ) const RAW_HTML = ` <a class="badge-evt badge-track" data-evt="PostList,TapPost,Tag,,PostTitle" data-track="post,v,,,d,aKDjw1N,l" data-entry-id="aKDjw1N" data-position="1" href="/gag/aKDjw1N" target="_blank"> When you mix MJ with Got </a> <a c...
/* Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ package main import ( "fmt" "strings" ) func main() { s := "uqinntq" fmt.Println(lengthOfLongestSubstring(s)) } func lengthOfLongestSubstring(s string) int { ma...
package slacktest import ( "testing" slack "github.com/nlopes/slack" "github.com/stretchr/testify/assert" ) func TestPostMessageHandler(t *testing.T) { s := NewTestServer() go s.Start() slack.SLACK_API = s.GetAPIURL() client := slack.New("ABCDEFG") channel, tstamp, err := client.PostMessage("foo", t.Name(), ...
// storage package models import ( "container/list" "fmt" ) const ( MAX_USER = 100 // max user in this system MAX_PLAYER = 10 // max player in one court ) // error state code type ErrCode int const ( NO_ERR = iota ERR_MAX_USER ERR_ANY = -1 ) // define interactive messges with external type MsgID int con...
package main import ( "context" "fmt" "io" "log" "net/http" "net/url" "os" "time" dapr "github.com/dapr/go-sdk/client" "github.com/dapr/go-sdk/service/common" daprd "github.com/dapr/go-sdk/service/http" "github.com/ohler55/ojg/jp" "github.com/ohler55/ojg/oj" "github.com/rs/xid" ) func main() { logger ...
// Copyright 2018 Lars Hoogestraat // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package middleware import ( "encoding/json" "net/http" "git.hoogi.eu/snafu/go-blog/httperror" "git.hoogi.eu/snafu/go-blog/logger" "git.hoogi.eu/snafu/go-blog/models" ) // J...
package main import ( _ "git.code.oa.com/trpc-go/trpc-filter/debuglog" _ "git.code.oa.com/trpc-go/trpc-filter/recovery" "git.code.oa.com/trpc-go/trpc-go" thttp "git.code.oa.com/trpc-go/trpc-go/http" "git.code.oa.com/trpc-go/trpc-go/log" "git.woa.com/trpc-go/helloworld/pkg" "git.woa.com/trpc-go/helloworld/pkg/ad...
package fill import "fmt" type exampleStruct struct { FieldA string FieldB bool FieldC int } type parentStruct struct { exampleStruct Struct exampleStruct InterfaceStruct exampleStruct MapStruct map[string]string } var interfaceData map[string]interface{} func ExampleFill_interfaceData() { i...
/* The Challenge Create a program that brute-force* decodes the MD5-hashed string, given here: 92a7c9116fa52eb83cf4c2919599c24a which translates to code-golf The Rules You may not use any built-in functions that decode the hash for you if the language you choose has such. You may not use an online service to...
/* Create a function that keeps only strings with repeating identical characters (in other words, it has a set size of 1). Examples identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"]) ➞ ["aaaaaa", "d", "eeee"] identicalFilter(["88", "999", "22", "545", "133"]) ➞ ["88", "999", "22"] identicalFilter(["xxxxo", "oxo"...
package countAndSay import "strconv" func countAndSay(n int) string { prev, cur := "1", "1" for i := 1; i < n; i++ { cur = "" num, value, nextPos := 0, "", 0 for nextPos != -1 { num, value, nextPos = calc(prev, nextPos) cur += strconv.Itoa(num) + value } prev = cur } return cur } func calc(s stri...
package backend import ( "encoding/json" "io/ioutil" "log" "os" "sync" pkgerr "github.com/pkg/errors" "github.com/square/beancounter/deriver" "github.com/square/beancounter/reporter" ) // FixtureBackend loads data from a file that was previously recorded by // RecorderBackend type FixtureBackend struct { ad...
package gstreams import ( "context" "fmt" "sync" "github.com/davecgh/go-spew/spew" "github.com/twmb/franz-go/pkg/kgo" ) const ( stateCreated = iota stateStarting statePartitionsRevoked statePartitionsAssigned stateRunning statePendingShutdown statePending ) type StreamThread struct { tasks map[string]m...
package apiclient import ( "context" workflowpkg "github.com/argoproj/argo/pkg/apiclient/workflow" ) type logsIntermediary struct { abstractIntermediary logEntries chan *workflowpkg.LogEntry } func (c *logsIntermediary) Send(logEntry *workflowpkg.LogEntry) error { c.logEntries <- logEntry return nil } func (...
package main import ( "net/http" "github.com/GeertJohan/go.rice" "github.com/insionng/vodka" ) func main() { handler := http.StripPrefix( "/static/", http.FileServer(rice.MustFindBox("app").HTTPBox()), ) e := vodka.New() e.Get("/static/*", func(c *vodka.Context) error { handler.ServeHTTP(c.Response().Writ...
package main import "testing" func TestP62(t *testing.T) { v := solve() out := 127035954683 if v != out { t.Errorf("P62: %v\tExpected: %v", v, out) } }
//go:generate go run generate.go package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "regexp" "sort" "strings" "github.com/elliotchance/pie/functions" ) func check(err error) { if err != nil { panic(err) } } func getIdentName(e ast.Expr) string { switch v := e.(type) { case...
package engine import ( "html/template" "path/filepath" "strings" log "github.com/Sirupsen/logrus" "github.com/gin-gonic/contrib/renders/multitemplate" "github.com/gin-gonic/gin" "github.com/GoPex/caretaker/controllers" "github.com/GoPex/caretaker/helpers" ) // Application struct holding everything needed t...
/* Package signal manages signal handling. */ package signal import ( "os" "os/signal" "syscall" ) // Ignore sets all signals to be ignored func Ignore() { signal.Ignore() } // Hup sets f() to be run on receipt of SIGHUP // SIGHUP is meant to be used to refresh program configuration func Hup(f func()) { sighup...
// Copyright 2015 Dejian Xu. All rights reserved. /* 缠中说禅走势中枢某级别走势类型中,被至少三个连续次级别走势类型 所重叠 的部分。 具体的计算以前三个连续次级别的重叠为准, 严格的公式可以这样表示 次级别的连续三个走势类型 A、B、C,分别的高、低点是 a1\a2,b1\b2,c1\c2。 则,中枢的区间就是(max(a2,b2,c2),min(a1,b1,c1)) 而实际上用目测就 可以,不用这么复 杂。 注意,次级别的前三个走势类型都是完成的才构成该级 别的缠中说禅走势中枢, 完成的走势类型,在次级别图上是很明显的,根本就不 用着再看次级别下面级别 的图了。 缠中说...
// +build unit package api import ( "flag" "github.com/open-horizon/anax/exchange" "github.com/open-horizon/anax/persistence" "testing" ) func init() { flag.Set("alsologtostderr", "true") flag.Set("v", "7") // no need to parse flags, that's done by test framework } func Test_CreateService0(t *testing.T) { ...
package app // env vars settings.yaml type Specification struct { // Common App variables AppName string `split_words:"true" default:"LocalOrderNumberGenerator"` GitHash string `split_words:"true" default:"Github-Hash"` Branch string `split_words:"true" default:"Github-Branch"` BuildN...
package picker import ( "context" "testing" "time" ) func sleepAndSend(delay int, in chan<- interface{}, input interface{}) { time.Sleep(time.Millisecond * time.Duration(delay)) in <- input } func sleepAndClose(delay int, in chan interface{}) { time.Sleep(time.Millisecond * time.Duration(delay)) close(in) } ...
package gmgo import ( "fmt" "testing" "time" "github.com/globalsign/mgo/bson" ) func testDBSession() *DbSession { dbConfig := DbConfig{HostURL: "mongodb://localhost:27017/phildb-prod", DBName: "phildb-prod", UserName: "", Password: "", Mode: 1} err := Setup(dbConfig) if err != nil { fmt.Printf("Connection f...
package cmd import "github.com/urfave/cli" var MXJobSubCommand = cli.Command{ Name: "mxjob", Aliases: []string{"mx"}, Usage: "submit a MXJob as training job.", Action: func(c *cli.Context) error { return nil }, }
package gmx // syscall.Rusage instrumentation for linux import "syscall" import "time" // constant copied from C header <linux/resource.h> to avoid requiring cgo // (this is a kernel API, so it is going to be very very stable) const RUSAGE_SELF = 0 func init() { // publish the total CPU time (userspace+system) use...
package main import "fmt" func main() { nums := []int{2, 7, 11, 15} target := 9 fmt.Println(twoSum1(nums, target)) fmt.Println(twoSum2(nums, target)) } func twoSum1(nums []int, target int) []int { m := make(map[int]int) for idx, num := range nums { if v, found := m[target-num]; found { return []int{nums...
package dhmiddleware import ( "github.com/cyongxue/magicbox/xhiris/xhdiagnose" "github.com/cyongxue/magicbox/xhiris/xhlog" "github.com/kataras/iris/v12" "sync" "time" ) // todo: 其他同样类似算法实现 // https://mp.weixin.qq.com/s/5wPpHi8wwaGjen71qXon_A type LimitUtil struct { limitNumber int64 // 触发受限阈值 minSafeTime int6...
package main import "fmt" type pessoa struct { nome string idade int } type dentista struct { pessoa dentesArrancados int salario float64 } type arquiteto struct { pessoa tipoConstrucao string tamanhoLoucura string } type profissional interface { saudacao() } func (d dentista) saudacao() { fmt...
package devto import "testing" func TestRetrieveTags(t *testing.T) { client := NewClient("") opt := &RetrieveTagsOption{ Page: 1, } tags, err := client.RetrieveTags(opt) if err != nil { t.Fatal(err) } if tags[0].Name != "javascript" { t.Errorf("Got wrong name expect: %s, actual: %s\n", "javascritp", tag...
/* SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2019 Intel Corporation */ package ngcnef_test import ( "context" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ngcnef "github.com/open-ness/epcforedge/ngc/pkg/nef" ) var _ = Describe("NefServer", func() { var ( ctx context.Context cancel f...
package requests import "time" var _ = time.Time{} type CreateGithubCommit struct { RepoName string Comments string UserName string BranchName string } type UpdateGithubCommit struct { RepoName string Comments string UserName string BranchName string } func (c *CreateGithubCommit) Valid() error...
package main import "fmt" func main() { printPointerMessage() } func printPointerMessage() { count := 20 countPointer := &count pointerValue := *countPointer fmt.Printf("countPointer: %x\n", countPointer) fmt.Printf("countPointerValue: %d", pointerValue) }
package feed import ( "camp/feed/api" "camp/feed/service" "camp/lib" "encoding/json" "github.com/globalsign/mgo/bson" "github.com/simplejia/clog/api" "net/http" ) type AddReq struct { Txt string `json:"txt"` } func (addReq *AddReq) Regular() (ok bool) { if addReq == nil { return } if addReq.Txt == "" {...
// ------------------------------------------------------------------- // // salter: Tool for bootstrap salt clusters in EC2 // // Copyright (c) 2013-2014 Orchestrate, Inc. All Rights Reserved. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // exce...
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package light import ( "github.com/hecate-tech/engine/core" "github.com/hecate-tech/engine/gls" ) // ILight is the interface that must be implem...
/* Package setupserver assists in setting up TLS credentials for a server. Package setupserver provides convenience functions for setting up a server with TLS credentials. The package loads client and server certificates from files and registers them with the lib/srpc package. The following command-line flags ar...
package main import ( "fmt" ) func main() { // pow := multiply("1099511627776", "1099511627776") // fmt.Println(pow, getDigitsSum(pow)) pow := multiply("2", "1") n := 40 for i := 2; i <= n; i++ { pow = multiply(pow, "2") fmt.Println("i=", i, pow) } fmt.Println("n=", n, getDigitsSum(pow), pow) }
package main import "fmt" func main() { sol := average([]float64{1.12341234, 2.4234, 3.24234, 4.5342534, 6.3245345}) fmt.Println(sol) } func average(slice []float64) (avg float64) { var sum float64 for _, val := range slice { sum += val } avg = sum / float64(len(slice)) return } func bubbleSort(slice []i...
package main import ( "crypto/tls" "crypto/x509" "github.com/streadway/amqp" "io/ioutil" "log" ) func main() { // To get started with SSL/TLS follow the instructions for adding SSL/TLS // support in RabbitMQ with a private certificate authority here: // // http://www.rabbitmq.com/ssl.html // // Then in you...
/* Given a string, create a function which outputs an array, building and deconstructing the string letter by letter. See the examples below for some helpful guidance. Examples constructDeconstruct("Hello") ➞ [ "H", "He", "Hel", "Hell", "Hello", "Hell", "Hel", "He", "H" ] constructDeconstruct("edab...
package blog import ( "net/http" ) type blogView struct { } func NewBlogView() *blogView { v := new(blogView) return v } func (v *blogView) Render(responseWriter http.ResponseWriter) error { var err error _, err = responseWriter.Write([]byte("<html><head></head><body>")) if err != nil { return err } _, er...
package cmd import ( "github.com/profiralex/go-bootstrap-redis/pkg/config" "github.com/spf13/cobra" ) // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "go-bootstrap-redis", Short: "bootstrapped golang api", Long: "bootstrapped golang api", } // Exe...
package main import ( "reflect" "testing" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/grpc/greeter" "golang.org/x/net/context" ) func TestGreeter_Greet(t *testing.T) { type fields struct { Exclaim bool } type args struct { ctx context.Context r *greeter.GreetRequest } ...
package main import ( "log" ) type ConnectionLimiter struct { concurrentConn int bucket chan int } func NewConnLimiter(cc int) *ConnectionLimiter { return &ConnectionLimiter{ concurrentConn: cc, bucket: make(chan int, cc), } } func (cl *ConnectionLimiter) GetConn() bool { if len(cl.bucket)...
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0. package restore_test import ( "context" "testing" "github.com/pingcap/kvproto/pkg/metapb" recovpb "github.com/pingcap/kvproto/pkg/recoverdatapb" "github.com/pingcap/tidb/br/pkg/conn" "github.com/pingcap/tidb/br/pkg/gluetidb" "github.com/pingcap/tidb/br...
package main import "fmt" func sendData(sendch chan<- int) { sendch<- 10 } func main() { cha1 := make(chan int) go sendData(cha1) //cha1<-10 fmt.Println(<-cha1) }
package sessions import ( "time" "github.com/rs/xid" ) // Session abstracts a session made of a last seen record and an uid type Session struct { lastSeen time.Time uid string } // sessionMap abstracts a hash table of multiple Session sorted by their flow data type sessionMap map[string]*Session var ( //...
package main import ( "log" "github.com/pressly/goose" "github.com/snapiz/go-vue-starter/packages/cgo" "github.com/spf13/cobra" ) func init() { root.AddCommand(&cobra.Command{ Use: "db:down", Short: "Rollback database schema", Run: func(cmd *cobra.Command, args []string) { db, err := cgo.NewDB("", fa...
package mongo import ( // Standard Library Imports "testing" // Internal Imports "github.com/matthewhartstonge/storage" ) func TestCacheMongoManager_ImplementsStorageConfigurer(t *testing.T) { c := &CacheManager{} var i interface{} = c if _, ok := i.(storage.Configurer); !ok { t.Error("CacheManager does no...
package main import ( "fmt" "sync" ) // Moves creates the moves that one person can make from one brick to another func moves() (m sync.Map) { var fromKey string var toMoves []string for x := 10; x <= 50; x++ { for y := 10; y <= 50; y++ { for z := 10; z <= 50; z++ { fromKey = fmt.Sprintf("%v_%v_%v", ...
package main import ( "fmt" "io/ioutil" "strconv" "strings" ) func part2() { // Assumes current working directory is `day-01/`! fileContent, err := ioutil.ReadFile("puzzle-input.txt") if err != nil { fmt.Println(err) } frequencyChangeList := strings.Split(string(fileContent), "\n") var resultingFrequenc...
package controller import ( "github.com/labstack/echo" "net/http" ) func Aboutus(c echo.Context) error { //session, _ := session.Get("session", c) //authKey := session.Values["authKey"] //if authKey == nil { // return c.Redirect(http.StatusMovedPermanently, "/login") //} //session.Save(c.Request(), c.Response...
package main import "fmt" func f( x float64) float64{ sum := 0.0 for i := 0; i < int(x)/10; i++{ sum += float64(i) } return sum } func trap( a float64, b float64, h float64) float64{ return (f(a)+f(b))*h } func main(){ var sum float64 = 0 n := 200.0 h := 1000000000.0/n var mesh [201]float64 for i := 0; ...
package kafka import ( "github.com/Shopify/sarama" "github.com/astaxie/beego/logs" "log" "logCollector/config" "logCollector/elasticsearch" "sync" ) var consumer sarama.Consumer func InitKafka(){ var err error consumer, err = sarama.NewConsumer(config.KafkaAddressList, nil) if err != nil { log.Fatal(err) ...
package 二分 import "sort" // ---------------------------- 方法1: 暴力版 ---------------------------- const INF = 1000000000 func findTheDistanceValue(arr1 []int, arr2 []int, d int) int { return getDistanceValueOfFirstArrayToSecondArray(arr1, arr2, d) } func getDistanceValueOfFirstArrayToSecondArray(firstArr, secondArr ...