text
stringlengths
11
4.05M
package main import "fmt" func main() { //test(4) test2(4) } //当执行main函数的时候,开辟一个栈空间,执行test函数,此时4>2条件成立,此时该栈区的值是3,但是因为有else存在,所以fmt.Println(num1)不执行 //开辟新栈区,调用自身,此时3>2条件成立,此时该栈区的值是2,但是因为有else存在,所以fmt.Println(num1)不执行 //开辟新栈区,继续调用自身,2>2条件不成立,执行else后面的语句,此时该栈区的值是2, 所以执行fmt.Println(num1)为2 //当不再开辟栈空间了,函数会按照返回之后才能执行剩下...
// Copyright (c) 2020 Blockwatch Data Inc. // Author: alex@blockwatch.cc package puller import ( "github.com/zyjblockchain/sandy_log/log" "sync" "tezos_index/puller/models" "time" logpkg "github.com/echa/log" ) // var log logpkg.Logger = logpkg.Log func init() { DisableLog() } func DisableLog() { // log = ...
// Copyright (c) Alex Ellis 2017. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package handlers import ( "fmt" "io/ioutil" "net/http" "net/url" "github.com/gorilla/mux" "github.com/openfaas/faas/gateway/metrics" "github.com/openfaas...
package scrape import ( "encoding/json" "errors" "fmt" "reflect" "strings" "time" "github.com/slotix/dataflowkit/errs" "github.com/slotix/dataflowkit/fetch" "github.com/slotix/dataflowkit/splash" "github.com/slotix/dataflowkit/utils" "github.com/spf13/viper" ) // UnmarshalJSON casts Request interface{} ty...
package rest import ( "github.com/jinmukeji/jiujiantang-services/pkg/rest" "github.com/kataras/iris/v12" ) // GetVersion 获取服务版本信息 func (h *handler) GetVersion(ctx iris.Context) { rest.WriteOkJSON(ctx, iris.Map{ "version": "2.0.0", }) }
package aoc2015 import ( "bufio" "fmt" "strconv" "strings" "sync" "github.com/pkg/errors" ) // excludeTown returns the same slice of towns but without some specified value. func excludeTown(from []town, except ...town) []town { out := make([]town, 0, len(from)/2) // don't worry it'll realloc. for _, vv := ra...
package main import ( "fmt" ) func main() { xi := []int{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30} s := sum(xi...) fmt.Println("The total amount is:", s) } func sum(s ...int) int { fmt.Println(s) sum := 0 for i, v := range s { sum += v fmt.Pr...
/*Package openid implements web service middlewares for authenticating identities represented by OpenID Connect (OIDC) ID Tokens. For details on OIDC go to http://openid.net/specs/openid-connect-core-1_0.html The middlewares will: extract the ID Token from the request; retrieve the OIDC provider (OP) configuration and...
// Copyright 2021 PingCAP, Inc. Licensed under Apache-2.0. package build import ( "strings" "testing" "github.com/stretchr/testify/require" ) func TestInfo(t *testing.T) { info := Info() lines := strings.Split(info, "\n") require.Regexp(t, "^Release Version", lines[0]) require.Regexp(t, "^Git Commit Hash", l...
package client import ( "github.com/giantswarm/api-schema" ) type SearchRequest struct { Usernames []string `json:"usernames"` Emails []string `json:"emails"` UserIDs []string `json:"user_ids"` } type SearchResult struct { Size int `json:"size"` Items []User `json:"items"` } func (c *Client) Search(r...
package main import ( "encoding/json" "net/http" "fmt" ) type Message struct { Text string } type Job struct { Title string City string } func main() { http.Handle("/", http.FileServer(http.Dir("./static"))) http.HandleFunc("/about/", about) http.HandleFunc("/api/jobs/", jobs) http.ListenAndServe(":8080"...
package main import ( "flag" "fmt" "math/rand" "os" "strconv" ) func main() { filePath := flag.String("file", "../../files/input.txt", "where you want to save your file") num := flag.Int("n", 10000, "amount of numbers you want to generate to the file") flag.Parse() generateFile(*filePath, *num) } // Generat...
package storage import ( "context" "time" "github.com/mongodb/mongo-go-driver/mongo" ) // MongoStorage implements our storage interface type MongoStorage struct { *mongo.Client DB string Collection string } // NewMongoStorage initializes a MongoStorage func NewMongoStorage(ctx context.Context, connect...
package main import ( "bytes" "context" "fmt" "image" "net/http" "net/url" "os" "path" "path/filepath" "strconv" "strings" "sync" "time" "github.com/BenLubar/nodejs-roundtripper" "github.com/gopherjs/gopherjs/js" "github.com/karlseguin/ccache" "golang.org/x/net/html" "golang.org/x/net/html/atom" ) ...
package handlers import ( "encoding/json" "net/http" ) func readiness(w http.ResponseWriter, r *http.Request) { status := struct { Status string }{ Status: "OK", } json.NewEncoder(w).Encode(status) }
package main import ( "fmt" h "github.com/gb_home/hw2/helper" prime "github.com/gb_home/hw2/primeNumber" ) func main() { fmt.Println("Написать функцию, которая определяет, четное ли число.") fmt.Println("isMod(4):", h.IsMod(4)) fmt.Println("isMod(7):", h.IsMod(7)) fmt.Println("Написать функцию, которая определ...
package providers import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "log" "os" // "time" ) var ( db *sql.DB ) const ( ADMIN = "a" MODER = "m" USER = "u" NOUSER = "n" ) //Define modules behaviors: type ( UserTemplate struct { Name, Phone, Email, Password_hash, Approve_token string Update...
/** *packet def *[LEN_16|CMDID_16|ID_32|FROM_16|TO_16|VCODE_16|PV_8|CSRC_8] = 16 * *packet define file description * @type = msg,entity *<type = msg,cmd =110> *<field =nid,type=uint32 desc=""/> **/ package packet import ( "encoding/binary" "fmt" "github.com/colefan/gsgo/netio/iobuffer" ) const ( PACKET_PROXY_HEA...
package easyorm type Table struct { } func (t *Table) Count() (int, error) { return 0, nil } func (t *Table) Add(value interface{}) (interface{}, error) { return nil, nil } func (t *Table) Set(value interface{}) (interface{}, error) { return nil, nil } func (t *Table) Get(key interface{}) (interface{}, error) {...
/* Because I forgot to celebrate Pi Day (14.3), let's celebrate with π, e (Euler's number) and music! Challenge No, we don't have time to eat a pi-pizza, let's make a program. What you need is 500 digits of π, and 10 digits of e. The input is an integer n between 0 and 499 inclusive. Then you should loop through t...
package main import ( "bufio" "fmt" "os" ) // https://www.hackerrank.com/challenges/sherlock-and-valid-string func main() { reader := bufio.NewReaderSize(os.Stdin, 100001) l, _, _ := reader.ReadLine() rf := make([]int, 26) for _, i := range l { rf[i-'a']++ } a := -1 ac := 0 b := -1 bc := 0 fail := fa...
package learnfunc import "testing" func TestFuncParams(t*testing.T){ array1 := [3]string{"a","b","c"} t.Logf("The array:%v\n",array1) array2 := modifyArray(array1) t.Logf("The array:%v\n",array2) t.Logf("The array:%v\n",array1) slice1 := []string{"x","y","z"} t.Logf("The slice:%v\n",slice1) slice2 := modify...
package alert import ( "crypto/tls" "fmt" "log" "net" "net/smtp" "strconv" "strings" ) //return a smtp client func Dial(addr string) (*smtp.Client, error) { conn, err := tls.Dial("tcp", addr, nil) if err != nil { log.Println("Dialing Error:", err) return nil, err } //分解主机端口字符串 host, _, _ := net.SplitH...
package lambdatohttp import ( "context" "github.com/aws/aws-lambda-go/events" "github.com/gorilla/mux" "io" "net/http" "net/url" "strings" ) func ServeRequest(router *mux.Router, ctx context.Context, req events.APIGatewayProxyRequest) events.APIGatewayProxyResponse { customHttpResponse := customHttpResponse{ ...
package main import ( "fmt" "io/ioutil" "net/http/httptest" "strings" "testing" ) func TestNewServer(t *testing.T) { s := NewServer(337, "something", 123) if s.port != 337 { t.Fatal("Invalid port found!") } if s.redisDB == nil { t.Fatal("Invalid redis db client!") } if s.getMatch == nil { t.Fatal(...
package main import ( "bytes" "compress/gzip" "io/ioutil" pb "learn_go/sockets/heartpackage/secondtest/protocol" "log" "net" "os" "time" "google.golang.org/protobuf/proto" ) var ( globalMainTable = &pb.MainTable{} ) func GravelChannel(bytes []byte, message chan byte) { for index, v := range bytes { if...
package middlewares import ( "errors" "fmt" "github.com/Highway-Project/highway/logging" "net/http" ) type Middleware interface { Process(handler http.HandlerFunc) http.HandlerFunc } type MiddlewareParams struct { Params map[string]interface{} } func (mp *MiddlewareParams) GetStringList(key string) (res []str...
package main import ( "bufio" "flag" "fmt" "github.com/PacketFire/go-ircd/parser" "log" "math/rand" "net" "os" "strings" "sync" "time" ) func init() { rand.Seed(time.Now().UTC().UnixNano()) } func main() { flag.Parse() defer func() { if r := recover(); r != nil { log.Printf("main: recovered from ...
package main import ( "testing" "github.com/stretchr/testify/require" ) func Test_A(t *testing.T) { testCases := []struct { input string expectedOutput int }{ {"1,3,2", 1}, {"2,1,3", 10}, {"1,2,3", 27}, {"2,3,1", 78}, {"3,2,1", 438}, {"3,1,2", 1836}, } for _, testCase := range testCas...
package parser type StationDetails struct { // Internal unique identifier. Id int // Name of the station as it is locally known; see info_* for translations. Name string // Guaranteed to be unique across all the suggestable stations; see `is_suggestable`. Slug string // The UIC code of the station. UIC stri...
package k8sml type K8sML interface { GetID() string GetVariableValue(variable string) interface{} }
package main import "testing" func TestP48(t *testing.T) { cases := []struct { in1, in2 int out int }{ {10, 10, 405071317}, {1000, 10, 9110846700}, } for _, c := range cases { v := selfPower(c.in1, c.in2) if v != c.out { t.Errorf("P48: %v\tExpected: %v", v, c.out) } } }
package main import ( "fmt" "log" "net/http" ) func listenforchecks() { http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") }) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", globalFlags.Port), nil)) }
// Copyright (C) 2017 Google 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 t...
package collectors import ( "time" "github.com/cloudfoundry-community/go-cfclient" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/log" ) type OrganizationsCollector struct { namespace string environment stri...
package msgHandler import ( "encoding/json" cmn "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/common" ) func (h *TDMMsgHandler) HandleNewRoundStepMsg(tdmMsg *cmn.TDMMessage) error { nrsMsg := &cmn.NewRoundStepMessage{} ConsLog.Infof(LOGTABLE_CONS, "HandleNewRoundStepMsg nrsMsg:", nrsMsg) err := json...
package leetcode import "testing" func TestRotatedDigits(t *testing.T) { if rotatedDigits(10) != 4 { t.Fatal() } }
package main import ( "context" "fmt" "github.com/micro/go-micro" srvHello "lemon_service/proto/hello" ) func main() { //先将自己注册到注册中心去 service := micro.NewService(micro.Name("go.micro.srv.clent")) //初始参数 service.Init() //创建 Hello对象客户端实例 client := srvHello.NewHelloService("go.micro.srv.Hello",service.Cli...
package base const ( HeaderErrorMessage = "X-Warp10-Error-Message" HeaderElapsed = "X-Warp10-Elapsed" HeaderErrorLine = "X-Warp10-Error-Line" HeaderFetched = "X-Warp10-Fetched" HeaderOperations = "X-Warp10-Ops" )
package brave import ( "fmt" "net/http" "github.com/jinzhu/gorm" ) func MigrateDatabase(db *gorm.DB) { db.AutoMigrate(&MangaInfo{}) db.AutoMigrate(&ChapterInfo{}) db.AutoMigrate(&PageInfo{}) } func GetMangaList(db *gorm.DB) []MangaInfo { var mangaList []MangaInfo db.Find(&mangaList) return mangaList } var...
package auth import portainer "github.com/portainer/portainer/api" func getUserEndpointAuthorizations(user *portainer.User, endpoints []portainer.Endpoint, endpointGroups []portainer.EndpointGroup, roles []portainer.Role, userMemberships []portainer.TeamMembership) portainer.EndpointAuthorizations { endpointAuthoriz...
package domain const ( SUCCESS_CODE = "0" SUCCESS_MESSAGE = "success" ) type BaseResponse struct { Code string `json:"code"` Message string `json:"message"` } type AddInstanceRsp struct { BaseResponse Data InstanceInfo `json:"data"` } type ListInstanceResponse struct { BaseResponse ...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-03 16:03 * Description: *****************************************************************/ package netstream import ( "github.com/go-xe2/x/core/lo...
package engine import ( "fmt" "net" "sync" "time" log "github.com/golang/glog" ) // TrackerEntry contains the Src and Dst IPs, as well as a map of Dst Ports // and how many times that port was scanned. type TrackerEntry struct { DstIP *net.IP SrcIP *net.IP Ports map[int]int expiry time.Time } // Tracker...
package version import ( "strings" "github.com/Masterminds/semver/v3" "github.com/pkg/errors" ) type DataplaneCompatibility struct { Envoy string `json:"envoy"` } type Compatibility struct { KumaDP map[string]DataplaneCompatibility `json:"kumaDp"` } var CompatibilityMatrix = Compatibility{ KumaDP: map[string...
package helpers import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" ) func TestSha1HexDigest(t *testing.T) { assert := assert.New(t) s1, err := Sha1HexDigest("tonic") assert.NoError(err) assert.Equal(s1, "dfe953579d49b555adf16d1823a71a8e463351c2") s2, err := Sha1HexDi...
package game_map import ( "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/animation" "github.com/steelx/go-rpg-cgm/state_machine" "reflect" ) type CSStandBy struct { Name string Character *Character CombatState *CombatState Entity *Entity Anim animation.Animation AnimId...
package main import "fmt" // 罗马数字有如下符号: // 基本字符 I V X L C D M // 对应阿拉伯数字 1 5 10 50 100 500 1000 // 计数规则: // 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3 // 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8 // 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4 // 正常使用时,连续的数字重复不得超过三次 // 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规...
package main import ( "flag" "fmt" "os" "runtime/pprof" "sync" ) type counter struct { count int } var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") func main() { flag.Parse() f, err := os.Create(*cpuprofile) if err != nil { panic(err) } pprof.StartCPUProfile(f) // 開始CPU...
package plantuml import "io" const ThemeCerulean = "https://raw.githubusercontent.com/bschwarz/puml-themes/master/themes/cerulean/puml-theme-cerulean.puml" type Diagram struct { includes []string renderables []Renderable } func NewDiagram() *Diagram { d := &Diagram{} return d } func (d *Diagram) Add(r ...Re...
// 25. Break "random access read/write" AES CTR package main import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "os" ) const secret = "YELLOW SUBMARINE" func main() { files := os.Args[1:] if len(files) == 0 { if err := decryptCTR(os.Stdin); er...
package leetcode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func inOrder(cur *TreeNode, c chan *TreeNode) { if cur != nil { inOrder(cur.Left, c) c <- cur inOrder(cur.Right, c) } } func minDiffInBST(root *TreeNode) i...
package analysis import ( "fmt" "github.com/PuerkitoBio/goquery" "strings" ) func AnalysisHot(body string) ([] map[string] string, error) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(body)) if err != nil { return nil, err } result := make([]map[string]string, 10) doc.Find("span.item_title"...
package ttt_test import ( "github.com/abdulrahmank/solver/tic_tac_toe/ttt" "testing" ) func TestBoard_Init(t *testing.T) { board := ttt.Board{} board.Init(3, 3) for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if board.Cells[i][j].Row != i && board.Cells[i][j].Column != j { t.Errorf("Expected %d, %d, ...
package config const ( TradeInfoFile = "./stockInfo.txt" ) const ( FirstTagIndex = iota + 1 SecondTagIndex ThirdTagIndex )
package lecimg import ( "image" "log" "github.com/disintegration/gift" "github.com/mitchellh/mapstructure" ) type ResizeOption struct { WidthScale float64 HeightScale float64 ScaleCover bool } func NewResizeOption(m map[string]interface{}) (*ResizeOption, error) { option := ResizeOption{} err := mapstru...
package full import ( "github.com/filecoin-project/specs-actors/v4/actors/builtin" "github.com/ipfs/go-cid" ) func BuiltinName4(code cid.Cid) string{ return builtin.ActorNameByCode(code) }
package main // This is a simple file server. For security, it support non-hierarchy directory (flat directory structure, no sub // directories). // The files are stored in the "files" directory as gzip files and served with the "Content-Encoding: gzip" HTTP // response header (if the "accept-encoding: gzip" HTTP requ...
package devops import "testing" func TestNewFortune(t *testing.T) { fortune, err := NewFortune() if err != nil { t.Errorf("E! %v", err) } if len(fortune) < 1 { t.Error("fortune is empty") } }
package parse import ( "fmt" "strconv" "testing" ) func TestParseIntToFloatUnits(t *testing.T) { cases := []struct { desc string input uint64 wantNum float64 wantUnits string }{ { desc: "no limit to TB", input: 2000 * Terabyte, wantNum: 2000, wantUnits: TB, }, { ...
/* For license and copyright information please see LEGAL file in repository */ package approuter // PingPeer : Endpoints can use PING to verify that their peers are still alive or to check reachability to the peer. func PingPeer() { // If the payload is not empty, the recipient MUST generate a PONG frame containing...
package di import "strings" func parseTag(tag string) (name string, optional bool) { options := strings.Split(tag, ",") if len(options) == 0 { return "", false } if len(options) == 1 && options[0] == "optional" { return "", true } if len(options) == 1 { return options[0], false } if len(options) == 2 &&...
// Copyright 2017 Jeff Foley. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package sources import ( "fmt" "regexp" "time" "github.com/OWASP/Amass/amass/core" "github.com/OWASP/Amass/amass/utils" ) // IPv4Info is data source object type t...
// Package v1alpha1 contains API Schema definitions for the pulumi v1alpha1 API group // +k8s:deepcopy-gen=package,register // +groupName=pulumi.com package v1alpha1
package piscine import "github.com/01-edu/z01" func IsNegative(nb int) { trueval := 'T' falsval := 'F' if nb >= 0 { z01.PrintRune(falsval) z01.PrintRune(10) } else { z01.PrintRune(trueval) z01.PrintRune(10) } }
package controlplane import ( "context" "net" "net/http" "net/http/pprof" "net/url" "time" envoy_service_discovery_v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" "github.com/gorilla/mux" "github.com/rs/zerolog" "golang.org/x/sync/errgroup" "google.golang.org/grpc" "google.golang.or...
// Copyright (c) 2023 Target Brands, Inc. All rights reserved. // // Use of this source code is governed by the LICENSE file in this repository. package vela import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "reflect" "strconv" "strings" "time" "github.com/buildkite/yaml" "github.com/go-ve...
package wallet import ( "errors" "github.com/appditto/pippin_nano_wallet/libs/database" "github.com/appditto/pippin_nano_wallet/libs/database/ent" "github.com/appditto/pippin_nano_wallet/libs/database/ent/account" "github.com/appditto/pippin_nano_wallet/libs/utils" "github.com/go-redis/redis/v9" ) var ErrWalle...
package gofile type GetServer struct { Status string `json:"status"` Data struct { Server string `json:"server"` } `json:"data"` } type Upload struct { Status string `json:"status"` Data struct { DownloadPage string `json:"downloadPage"` Code string `json:"code"` ParentFolder st...
package lambdacalculus import ( "testing" ) var one = Succ(Zero) var two = Succ(one) var three = Succ(two) var four = Succ(three) func TestZero(t *testing.T) { res := Zero(f)(x) if res != 0 { t.Errorf("Zero does not return 0") } } func TestSucc(t *testing.T) { res := Succ(Zero)(f)(x) if res != 1 { t.Error...
package words import ( "strings" "regexp" "github.com/deepdeeppink/tgbot/cfg" "github.com/deepdeeppink/tgbot/state" api "gopkg.in/telegram-bot-api.v4" ) type Phrase struct { SpellName string State state.State Message *api.Message } func NewPhrase(m *api.Message, userLevel int) *Phrase { var spellname strin...
/* * Copyright 2018-present Open Networking Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law ...
package filter // Labeled is used to access labels of an object type Labeled interface { GetLabels() map[string]string } // Temporary objects type staticlabeled struct { labels map[string]string } func (s staticlabeled) GetLabels() map[string]string { return s.labels } // GetLabeled returns a Labeled object that...
package main import ( "context" "fmt" "strings" "sync" pb "github.com/semi-technologies/contextionary/contextionary" core "github.com/semi-technologies/contextionary/contextionary/core" schema "github.com/semi-technologies/contextionary/contextionary/schema" "github.com/semi-technologies/contextionary/extensi...
package logging import ( "encoding/json" "net" "os" "sync" "testing" "time" . "github.com/anthonybishopric/gotcha" "github.com/sirupsen/logrus" ) func TestLoggingCanMergeFields(t *testing.T) { fields1 := logrus.Fields{ "foo": "a", "bar": "b", } fields2 := logrus.Fields{ "foo": "z", "baz": "q", } ...
package cmd import ( "github.com/go-openapi/loads" ) func load(filename string) (*loads.Document, error) { d, err := loads.JSONSpec(filename) if err != nil { return nil, err } return d, nil }
package tasks_test import ( "testing" "github.com/stretchr/testify/assert" "go.ua-ecm.com/chaki/tasks" ) func TestSanitize(t *testing.T) { assert := assert.New(t) dirty := &tasks.Config{ DBConnections: map[string]tasks.DBConnection{}, Tasks: map[string]tasks.Task{ "foo": tasks.Task{ Title: "Foo", ...
package collectors import ( "bufio" "os" cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger" lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric" // "log" "encoding/json" "errors" "strconv" "strings" "time" ) const IOSTATFILE = `/proc/diskstats` const IOSTAT_SYSFSPATH = `/sys/blo...
package main import ( "fmt" merge_trees "github.com/NGunthor/go_test/pkg/leetcode/merge-trees" ) func main() { tree1 := merge_trees.NewBinaryTree(1,2,3,4) tree2 := merge_trees.NewBinaryTree(1,2,3,4) result := merge_trees.NewTrees(tree1.GetHead(), tree2.GetHead()).MergeTrees() fmt.Println(result) }
package models type Preference struct { ClientID string `db:"client_id"` Count int `db:"count"` KindID string `db:"kind_id"` Email bool KindDescription string `db:"kind_description"` SourceDescription string `db:"source_description"` }
package main import ( "context" "flag" "fmt" "google.golang.org/grpc" "time" pb "ziyun/opstring-service/pb" r "ziyun/opstring-service/svc/client/grpc" ) func main() { flag.Parse() ctx := context.Background() conn, err := grpc.Dial("localhost:5040", grpc.WithInsecure(), grpc.WithTimeout(1*time.Second)) if e...
package primitives type Rectf struct { Min, Max [2]float32 } func MakeRectf(x1, y1, x2, y2 float32) Rectf { if x1 > x2 { x1, x2 = x2, x1 } if y1 > y2 { y1, y2 = y2, y1 } return Rectf{ Min: [2]float32{x1, y1}, Max: [2]float32{x2, y2}, } }
package happening import ( "fmt" "io/ioutil" "log" "os" "os/signal" "strconv" "syscall" ) func createPidFile(pidfile string) error { if pidString, err := ioutil.ReadFile(pidfile); err == nil { pid, err := strconv.Atoi(string(pidString)) if err == nil { if _, err := os.Stat(fmt.Sprintf("/proc/%d/", pid)...
package main import ( "fmt" "sync" ) //long lived struct that should always be its own goroutine, it is initialized as the entry point for new connections and, when //pairing is successful launches a game controller as a goroutine and sets the player connection to send packets there instead. type matchMakingModel s...
package buntdb import ( "github.com/b2wdigital/goignite/pkg/config" "log" ) const ( Path = "transport.client.buntdb.parh" SyncPolicy = "transport.client.buntdb.syncpolicy" AutoShrinkPercentage = "transport.client.buntdb.autoshrink.percentage" AutoShrinkMinSize = "transport.client.b...
package tick import ( "tokensky_bg_admin/conf" "tokensky_bg_admin/models" ) //维护用户地址维护 var tickTokenskyUserAddressUpSign bool = true func TickTokenskyUserAddressUp() error { if tickTokenskyUserAddressUpSign{ tickTokenskyUserAddressUpSign = false defer func() {tickTokenskyUserAddressUpSign=true}() for _, coin...
package system import ( "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) func Boot(address string) { go func() { e := echo.New() e.Use(middleware.CORS()) SetRoutes(e) //e.HidePort=true e.HideBanner = true e.Logger.Fatal(e.Start(address)) }() } func SetRoutes(e *echo.Echo) { e.GET(...
package main import ( "fmt" ) func pointer_test() { // to specify a pointer simply use & equivalent to a var x := 5 a := &x //print var fmt.Println(x) // print value to pointer fmt.Println(*a) // print address fmt.Println(&a) } func main() { pointer_test() }
package proxy import "github.com/sirupsen/logrus" func DefaultLogger() *logrus.Logger { log := logrus.New() log.Formatter = &logrus.JSONFormatter{} return log }
package main import ( "flag" "fmt" "log" "os" "path/filepath" "strconv" "strings" "time" "github.com/gholt/brimtime" "github.com/gholt/store" "github.com/pandemicsyn/ftls" "github.com/pandemicsyn/oort/api" "github.com/peterh/liner" "github.com/spaolacci/murmur3" "golang.org/x/net/context" "google.gola...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //84. Largest Rectangle in Histogram //Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the...
package http import ( "context" "io/ioutil" "log" "net/http" "strconv" "strings" "time" "code-cadets-2021/homework_2/task_01/internal/domain/models" ) const axilisFeedURL2 = "http://18.193.121.232/axilis-feed-2" type AxilisOfferFeedSecond struct { httpClient http.Client updates chan models.Odd } func ...
package main import ( "fmt" "net/http" "os" "path" "path/filepath" ) // AppHandlerFunc defines a function which acts as a context-aware HTTP handler // In case of error, it returns the error which is handled separately type AppHandlerFunc func(http.ResponseWriter, *http.Request, Context) error // AppHandler is ...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //65. Valid Number //Validate if a given string is numeric. //Some examples: //"0" => true //" 0.1 " => true //"abc" => false //"1 a" => false //"2e10"...
package models import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func Init() { db, err := gorm.Open("sqlite3", "test.db") if err != nil { panic("Failed to connect database") } db.AutoMigrate(&Board{}, &Thread{}, &Issue{}, &Error{}, &HistoryPoint{}) db.Close() } func DB() *gorm.D...
package health import ( "github.com/go-openapi/runtime/middleware" "github.com/movieManagement/gen/restapi/operations" "github.com/movieManagement/gen/restapi/operations/health" "github.com/movieManagement/swagger" ) // Configure setups handlers on api with Service func Configure(api *operations.MovieServiceAPI, ...
package main import "fmt" func foo() (int, int, int){ return 1,2,3 } func main(){ _, _, x := foo() fmt.Println(x) }
package addressbus import ( "testing" "github.com/KaiWalter/go6502/pkg/memory" ) func TestOnlyRam(t *testing.T) { const memSize = 0x200 // arrange bus := &MultiBus{} bus.InitBus(0x100) ram := memory.Memory{AddressOffset: 0, AddressSpace: make([]byte, memSize)} bus.RegisterComponent(0, len(ram.AddressSpace)...
package smtp import ( "crypto/tls" "fmt" "mime" "net" "net/smtp" "strings" ) // Stubbed out for tests. var ( netDialTimeout = net.DialTimeout tlsClient = tls.Client smtpNewClient = func(conn net.Conn, host string) (smtpClient, error) { return smtp.NewClient(conn, host) } bEncoding = mimeEncoder...
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...