text
stringlengths
11
4.05M
package main import ( "fmt" "net/http" ) var ( MaxWorker = 10 MaxQueue = 10 dispatcher *Dispatcher workers []*Worker ) /** 调度器 **/ type Dispatcher struct { WorkerPool chan chan Job JobQueue chan Job } func NewDispatcher() *Dispatcher { return &Dispatcher{ WorkerPool: make(chan chan Job, MaxWorker...
package logcollector import ( "context" "fmt" "os" "testing" "time" ) func TestNewCollector(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, logIdCtxKey{}, "2010") //output := os.Stdout output, err := os.OpenFile("run.log", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModeAppend) if err !=...
// Copyright 2016 Kranz. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package main import ( "os" "runtime" "gopkg.in/urfave/cli.v2" "github.com/rodkranz/fakeApi/cmd" "github.com/rodkranz/fakeApi/modules/setting" ) const VER = "1.4....
package elasticsearch import ( "elktools/cmd/utils" "fmt" "time" "github.com/desertbit/grumble" ) func AppFlags(f *grumble.Flags) { f.String("a", "address", defaultElasticURL, "set elastic search address") f.String("u", "username", "elastic", "set elastic search username") f.String("p", "password", "changeme"...
package leetcode func nextGreatestLetter(letters []byte, target byte) byte { min := byte(255) min2 := byte(255) for _, b := range letters { if b > target && b < min { min = b } if b < min2 { min2 = b } } if min != byte(255) { return min } return min2 }
package sender import ( "log" "github.com/b2wdigital/goignite/pkg/config" ) const ( Url = "transport.client.cloudevents.nats.sender.url" ) func init() { log.Println("getting configurations for http server") config.Add(Url, "http://127.0.0.1:4222", "define nats server") } func GetUrl() string { return confi...
package remotes import "github.com/deps-cloud/discovery/pkg/config" var _ Remote = &staticRemote{} // NewStaticRemote produces a new remote from static configuration func NewStaticRemote(cfg *config.Static) Remote { return &staticRemote{ cfg: cfg, } } type staticRemote struct { cfg *config.Static } func (s *s...
// Package batch is used for interacting with the Streamdal platform's API. This // backend is a non-traditional backend and does not implement the Backend // interface; it should be used independently. package streamdal import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/cookiejar" "net/url...
package tusdx import ( "github.com/go-xorm/xorm" "github.com/maxtech/tusdx/tusdx_model" ) type tusdFilesObject struct { } var tusdFilesDao *tusdFilesObject func (wfd *tusdFilesObject) TableName() string { return "tusd_files" } func (wfd *tusdFilesObject) getSessionByQueryMap(queryMap map[string]interfa...
package main import ( "time" ) const ( DAY_TIME = 24 * 60 * 60 HOUR_TIME = 60 * 60 MIN_TIME = 60 ) func timer() { logupdate_ticker := time.NewTicker(DAY_TIME * time.Second) for { select { case <-logupdate_ticker.C: logger_file_update() } } }
package flag_test import ( "github.com/hoenirvili/skapt/flag" gc "gopkg.in/check.v1" ) type flagSuite struct{} var _ = gc.Suite(&flagSuite{}) func (f flagSuite) TestValidate(c *gc.C) { flags := []flag.Flag{ {Short: "u"}, {Long: "url"}, {Short: "u", Long: "url"}, } for _, flag := range flags { err := f...
package util //import ( // "testing" //) //func TestIputil(t *testing.T) { // ips := GetInnerIP() // for _, ip := range ips { // t.Log("innerip:", ip.String()) // } // ips = GetOuterIP() // for _, ip := range ips { // t.Log("outerip:", ip.String()) // } // t.Log("ip:", IPStrToUInt("8.8.8.8")) //} ...
package model type Server struct { ClusterName string `json:"cluster_name"` AppName string `json:"app_name"` ServerName string `json:"server_name"` Ip string `json:"ip"` } type ServerNodes struct { servers []string }
package rpc import ( "context" "github.com/stretchr/testify/assert" "net/http" "net/url" "testing" ) func TestClient_GetConstants(t *testing.T) { client, err := NewClient(nil, "https://mainnet-tezos.giganode.io") assert.NoError(t, err) constants, err := client.GetConstantsHeight(context.Background(), 1) ass...
// Rest API Implementations package main import ( "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" ) //restWakeUpWithComputerName - REST Handler for Processing URLS /api/computer/<computerName> func restWakeUpWithComputerName(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "ap...
package main import ( "fmt" "zinx/src/zinx/ziface" "zinx/src/zinx/znet" ) /* 基于Zinx 框架来开发的 服务器端应用程序 */ // ping test 自定义路由 type PingRouter struct { znet.BaseRouter } //// Test PreRouter //func (this *PingRouter) PreHandle(request ziface.IRequest) { // fmt.Println("Call Router PreHandle...") // // request.GetCon...
// Copyright 2016 Walter Schulze // // 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...
package main import ( "context" "strconv" "github.com/juju/errors" "github.com/pingcap/tidb/kv" ) func HandleHashSet(db kv.Storage, key []byte, field []byte, value []byte) (interface{}, error) { txn, err := db.Begin() if err != nil { return nil, err } defer txn.Rollback() it, err := SeekPrefix(txn, key) ...
package main import ( "bufio" "os" "strconv" "strings" ) type Problem2A struct { } func (this *Problem2A) Solve() { Log.Info("Problem 2A solver beginning!") grid := &IntegerGrid2D{}; grid.Init(); // Populate the grid grid.SetValue(-1,-1,1); grid.SetValue(0,-1,2); grid.SetValue(1,-1,3); grid.SetValue(-1...
package server import ( "bytes" "context" "fmt" "github.com/gin-gonic/gin" "google.golang.org/grpc/metadata" "io/ioutil" "mysql-agent/common/logger" "mysql-agent/controller/domain" "net/http" ) func NewHttpServer(ip string, port int) *http.Server { return &http.Server{ Addr: fmt.Sprintf("%s:%d", ip, po...
package handler import ( "encoding/json" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/gorilla/mux" "net/http" ) // RetrieveKeys is the handler that will retrieve public keys directly from the mailserver func RetrieveKeys(w http.ResponseW...
package rest_test import ( "net/http/httptest" "github.com/phogolabs/rest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Respond", func() { It("renders json", func() { request := NewJSONRequest(nil) recorder := httptest.NewRecorder() rest.Respond(recorder, request, "hello"...
package util import "github.com/go-redis/redis/v8" var rdb *redis.Client func NewRdb() *redis.Client { if rdb == nil { rdb = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) } return rdb }
package markov import ( "strings" "github.com/abrisene/gocausal/distribution" "github.com/abrisene/gocausal/random" ) type Model struct { config *Config sequences [][]string states map[string]int grams map[string]*gram generator *random.Random } type Config struct { maxOrder int delimiter ...
package main func main() { //Variable data type //var card string = "Ace of Spades" //card = "Overrite Ace of Shades New" //function Call //card := newCard() //Slices and Array // cards := deck{newCard(), newCard()} // cards = append(cards, "Six of Shades") // fmt.Println(cards) // cards.print() // for i,...
package entity import ( "time" ) type OmsOrderReturnReason struct { Id int64 `json:"id" xorm:"pk autoincr BIGINT(20) 'id'"` Name string `json:"name" xorm:"default 'NULL' comment('退货类型') VARCHAR(100) 'name'"` Sort int `json:"sort" xorm:"default NULL INT(11) 'sort'"` Status int...
package cleanup import ( "fmt" "os" "path" "path/filepath" git "github.com/josa42/go-gitutils" zglob "github.com/mattn/go-zglob" ) // Keep : func Keep() { fmt.Println("Clean .gitkeep files") keeps, _ := zglob.Glob("**/.gitkeep") for _, keep := range keeps { dir := path.Dir(keep) files, _ := filepath.Gl...
package main import ( "fmt" "time" "math/rand" "ErrorHelper" "ErrorHelper/Core" ) var tsProgrammStart time.Time = time.Now() func init() { fmt.Printf("main.init() - initializing: %v ...\n", tsProgrammStart ) } func main() { rand.Seed( time.Now().UnixNano() ) fmt.Printf("%v - TestErrors running ...\n\n",...
package _746_Min_Cost_Climbing_Stairs func minCostClimbingStairs(cost []int) int { return minCostClimbingStairsDynamic(cost) } func minCostClimbingStairsDynamic(cost []int) int { if len(cost) == 0 { return 0 } if len(cost) == 1 { return cost[0] } if len(cost) == 2 { return minCost(cost[0], cost[1]) } co...
// interfaces: abstraksi tipe data yang telah dipesan/kontrak/teken/signatured // tujuan: struct berbeda akan tetapi dapat menggunakan kontrak yang sama // agar penggunaan ruang(rom/ram_ lebih efieien package main { "fmt", "math" } type geometri interface { // initialize type of identified function *later // kumpul...
package comm import ( "context" "sync/atomic" "github.com/dbolotin/deadmanswitch/ctyutil" "github.com/zclconf/go-cty/cty" ) type Msg struct { Ctx context.Context replyTo chan<- cty.Value valueFactory func() cty.Value value *cty.Value answered *int32 } func NewMessage(ctx context.Co...
package main import ( data "datamodel" "encoding/json" "flag" "fmt" "io/ioutil" "log" "log/syslog" "logger" "lolutil" "net/http" "runtime" "strconv" "strings" "time" ) // Constants var API_KEY = flag.String("apikey", "", "Riot API key") var CHAMPION_LIST = flag.String("summoners", "champions", "List of ...
// Copyright © 2018-2020 Wei Shen <shenwei356@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, mo...
package preoblem //定义链表的投节点 type ListNode struct { Val int Next *ListNode }
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package flare import ( "context" "fmt" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/pkg/errors" "github.com/diegobernarde...
package main import ( "github.com/pepeunlimited/authentication/internal/app/app1/server" "github.com/pepeunlimited/microservice-kit/jwt" "github.com/pepeunlimited/microservice-kit/misc" "log" "net/http" ) const ( Version = "0.1" ) func main() { log.Printf("Starting the AuthenticationServer... version=[%v]", V...
package main import ( "bufio" "log" "os/exec" "sync" "github.com/pkg/errors" ) // execCommand executes a commands and pipes its stdout and stderr out to the // git-initializer's own logs. func execCommand(cmd *exec.Cmd) error { stdoutReader, err := cmd.StdoutPipe() if err != nil { return errors.Wrap(err, "e...
/** * @license * Copyright 2018 Telefónica Investigación y Desarrollo, S.A.U * * 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 * * Unles...
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. package export import ( "strings" "time" "github.com/go-sql-driver/mysql" "github.com/pingcap/errors" "github.com/pingcap/tidb/br/pkg/utils" tcontext "github.com/pingcap/tidb/dumpling/context" "github.com/pingcap/tidb/util/dbutil" "go.uber.org/zap" )...
package main const DefaultTerminal = "win"
package charts import ( "github.com/go-echarts/go-echarts/v2/opts" "github.com/go-echarts/go-echarts/v2/render" "github.com/go-echarts/go-echarts/v2/types" ) // Liquid represents a liquid chart. type Liquid struct { BaseConfiguration BaseActions } // Type returns the chart type. func (*Liquid) Type() string { r...
// Copyright 2021 Google LLC. 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 applica...
package bt import ( "bytes" "encoding/binary" "fmt" "io" ) const ( // Protocol is "BitTorrent protocol" Protocol = "BitTorrent protocol" ) // ReadMessage read a message from stream func ReadMessage(reader io.Reader) ([]byte, error) { var length uint32 err := binary.Read(reader, binary.BigEndian, &length) i...
package tests import ( "encoding/json" "errors" "net/http" "net/http/httptest" "strings" "testing" "github.com/lenuse/mall/repository" "github.com/lenuse/mall/utils" "github.com/stretchr/testify/assert" "github.com/lenuse/mall" ) func TestCreateAdmin(t *testing.T) { repository.Init() defer repository.Cl...
package main import ( "fmt" "math" ) func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { sum := len(nums1) + len(nums2) res := 0.0 if sum%2 == 0 { mid1 := findKth(nums1, nums2, sum/2) mid2 := findKth(nums1, nums2, sum/2+1) res = (mid1 + mid2) / 2 } else { res = findKth(nums1, nums2, sum/2+1)...
package main import ( "flag" "fmt" "io/ioutil" "log" "os" llp "github.com/romshark/llparser" "github.com/romshark/llparser/examples/dicklang/parser" ) var flagFilePath = flag.String( "src", "./dicks.txt", "source file path", ) var flagPrintParseTree = flag.Bool( "ptree", false, "prints the parse-tree on...
package common import ( "errors" "net/url" ) // GetRequiredParam gets a query parameter and errors if nothing is found. func GetRequiredParam(params url.Values, paramName string) (val string, err error) { return getParam(params, paramName, true, "") } // GetDefaultParam gets a query parameter and retu...
package handlers import ( "io/ioutil" "net/http" "net/http/httptest" "testing" "time" ) func TestHome(t *testing.T) { w := httptest.NewRecorder() buildTime := time.Now().Format("20060102_03:04:05") commit := "some test hash" release := "0.0.8" h := home(buildTime, commit, release) h(w, nil) resp := w.Resu...
// Copyright 2015 Felipe A. Cavani. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Util package have a collection of functions to help standard lib // do some trivial stuffs. package util
package gfort import ( //"errors" "fmt" "os" "reflect" "github.com/pkg/errors" ) var suppress = false func SuppressWarning() { suppress = true } func ActivateWarning() { suppress = false } func Ignore(err error) { if !suppress { var e error if err == nil { e = errors.New("<gfort dummy error>") } ...
package pollbot import "fmt" const htmlVoteResult = `<html> <head> <title> Polling Service Confirmation </title> <style> body { padding: 50px; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; font-size: 22px; } .column { displa...
package main import ( "log" "os" "time" ) func main() { log2 := log.New(os.Stderr, "UTC ", log.LstdFlags|log.LUTC) c := time.NewTicker(10 * time.Second).C for ; ; <-c { log.Print("env TZ:", os.Getenv("TZ")) log.Print("time.Local:", time.Local) log.Print("Local Time:", time.Now()) log.Print("UTC Time:",...
package config import ( "github.com/BurntSushi/toml" "os" "path/filepath" "sync" ) const ConfigPath string = "../../conf/test.toml" var Configmaps *TomlConfig type TomlConfig struct { Kubeconf Kubeconf Node map[string]string Ssh SshConf } type SshConf struct { Port int Username string Password strin...
package volume import ( "fmt" "os" "path/filepath" "strconv" "strings" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" "github.com/syndtr/goleveldb/leveldb/util" ) type levelDBIndex struct { db *leveldb.DB } // level db params var ( blockCapacity = 8 compactionTableS...
package mount import ( "log" "os" "os/exec" ) func Unmount(path string) { if _, err := os.Stat(path); !os.IsNotExist(err) { // the mount point already exists! // attempt to unmount first, just in case umount := exec.Command("umount", path) if err := umount.Run(); err == nil { log.Println("unmounted", p...
// SPDX-License-Identifier: Apache-2.0 // Copyright © 2019 Intel Corporation package af import ( "encoding/json" "errors" "net/http" "strconv" ) func verifyAFTransID(afCtx *Context, transID string, p *ProblemDetails) (int, error) { var ( transIDInt int err error ) const ProblemTitle = "AF transa...
package log import ( "fmt" "github.com/sirupsen/logrus" "os" "time" ) //RenameLogFile 按日期分包 func RenameLogFile() { fileBase := "applog" dir := "./log/static/" lastDay := time.Now().Day() var oldfile *os.File defer func() { if oldfile != nil { oldfile.Close() } }() f := func() { now := time.Now() ...
package subscription import ( "context" "fmt" "sync" "github.com/syncromatics/kafmesh/internal/graph/model" "github.com/syncromatics/kafmesh/internal/graph/resolvers" watchv1 "github.com/syncromatics/kafmesh/internal/protos/kafmesh/watch/v1" "github.com/pkg/errors" "golang.org/x/sync/errgroup" "google.golan...
package sparkline import ( "fmt" "strconv" ) // SparkNumbers takes a list of numbers, converts them to floating points and // generates the sparkline chart from the data. There is a limited number of // bars provided by the Unicode standard, so there will be the case where // different numbers are shown in the char...
package models type Label struct { Id uint64 CategoryId uint64 Name string } type Category struct { Id uint64 Name string }
package main import ( "log" "os" "os/exec" "sync" "time" "github.com/bahusvel/ClusterPipe/common" "github.com/bahusvel/ClusterPipe/kissrpc" "github.com/urfave/cli" ) var controllerAddress string var controller *kissrpc.Client var thisCPD = common.CPD{} var procMutex = sync.RWMutex{} var processes = map[comm...
package main import ( "fmt" "github.com/Centny/gwf/util" "github.com/Centny/nms" "os" ) func main() { if len(os.Args) < 3 { fmt.Println("Usage: nms <-c|-s> <configure file>") os.Exit(1) return } var fcfg = util.NewFcfg3() fcfg.InitWithFilePath2(os.Args[2], true) switch os.Args[1] { case "-s": fmt.Pr...
package main import ( "bytes" "encoding/binary" "fmt" blockingester "github.com/decentralisedkev/Neo-Go-API/BlockIngester" "github.com/decentralisedkev/Neo-Go-API/database" "github.com/decentralisedkev/Neo-Go-API/node" ) func main() { db, _ := database.NewLDBDatabase("dirname", 0, 0) table := database.NewTa...
package main import ( "net" "os" proto "github.com/golang/protobuf/proto" log "github.com/sirupsen/logrus" ) func listenUDP() error { ip, port, err := ExtractIPInfo(os.Getenv("METRIC_PROXY_SERVER__UDP")) if err != nil { return err } addr := &net.UDPAddr{ IP: ip.IP, Port: port, Zone: ip.Zone, } ...
package linkedNumber import ( "fmt" ) //每个node所记录数据的进位值 const max = 1e9 //链表节点 type node struct { previousNode *node number int nextNode *node } //链表 type LinkedNumber struct { firstNode *node lastNode *node } //初始化链表 func Init(i int) LinkedNumber { firstNode, lastNode := buildNode(i) return Lin...
package main import ( "flag" "os" "github.com/codyspate/go_crawl" ) func main() { urlPtr := flag.String("url", "http://www.google.com/", "a url <string>") threadPtr := flag.Int("threads", 50, "number of threads <int>") flag.Parse() // Below is from Python version // 71stsog | http://71stsog.com/ | 71stsog.co...
package requests import ( "encoding/json" "testing" "github.com/mitchellh/mapstructure" "github.com/stretchr/testify/assert" ) func TestDecodeSendRequest(t *testing.T) { encoded := `{"action":"send","wallet":"1234","source":"nano_1","destination":"nano_2","bpow_key":"abc","amount":"1234"}` var decoded SendRequ...
/******************************************************************************* * Copyright 2021 Intel Corporation * * 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.o...
package go_utils // Positive modulo, returns non negative solution to x % d func Mod(x, d int) int { x = x % d if x >= 0 { return x } if d < 0 { return x - d } return x + d } func Max(a int, b int) int { if a > b { return a } return b } func Min(a int, b int) int { if a < b { return a } return b ...
package robot import ( "bytes" "strconv" ) // s xxxxxxbegin^_^end return ^_^ or nil func ParseParamBeginEnd(s, begin, end []byte) []byte { i := bytes.Index(s, begin) if i < 0 { return nil } s = s[i+len(begin):] if end == nil { return s } i = bytes.Index(s, end) if i < 0 { return nil } return s[:i]...
package routers import ( "github.com/gorilla/mux" kcontrol "goapi/work/controllers" ) var R *mux.Router func init() { R = mux.NewRouter() addRouter() } func addRouter() { R.HandleFunc("/", kcontrol.Test) R.HandleFunc("/test1", kcontrol.Test1) R.HandleFunc("/testjson", kcontrol.Testjson) R.HandleFunc("/tes...
package main import ( "bytes" "encoding/binary" "fmt" "reflect" "time" "unsafe" "github.com/elastic/beats/libbeat/logp" "github.com/elastic/beats/winlogbeat/sys" "github.com/elastic/beats/winlogbeat/sys/eventlogging" win "github.com/elastic/beats/winlogbeat/sys/wineventlog" "golang.org/x/sys/windows" ) co...
package main import ( "flag" "fmt" "os" ) func main() { dnssec := flag.Bool("dnssec", false, "Request DNSSEC records") port := flag.String("port", "53", "Set the query port") flag.Usage = func() { fmt.Printf("Usage %s [OPTIONS] [name ...]\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() if *dnssec {...
package textile var Avatars = ` { "name": "avatar", "pin": true, "links": { "large": { "use": ":file", "pin": true, "plaintext": true, "mill": "/image/resize", "opts": { "width": "320", "quality": "75" } }, "small": { "use": ":file", "pi...
package aiff import ( "bytes" "testing" ) func TestIEEE754Float80bit(t *testing.T) { var data [10]byte data = [10]byte{0x40, 0x0e, 0xac, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} var f IEEE754Float80bit f = data if f.LongValue() != 44100 { t.Fatalf("LongValue() is invalid: %d", f.LongValue()) } var data2 ...
// Copyright 2023 Google LLC. 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 applica...
package twch import ( "fmt" ) type Teams struct { client *Client } type Team struct { ID *int `json:"_id,omitempty"` Name *string `json:"name,omitempty"` Info *string `json:"info,omitempty"` DisplayName *string `json:"display_name,omitempty"` Logo *string `json:"logo,omitempty...
package main import "fmt" func main() { nums := []int{1, 2, 3, 4, 5, 6, 7} k := 3 rotate(nums, k) } func rotate(nums []int, k int) { // k大于nums if k > len(nums) { k = k % len(nums) } //原地旋转 copy(nums, append(nums[len(nums)-k:], nums[:len(nums)-k]...)) fmt.Println(nums) }
package main // Node and Edge type definition const ( NEURON int16 = 1 CONNECTION int16 = 1 )
package main const generatorCode1 = ` func main() { __buildHFile() __winLoader() __linuxLoader() {{ if .SafeMethods }} __winFastcall() __linuxFastcall() {{ end }} } func __buildHFile() { f, err := os.Create("{{ .TargetFile }}") if err != nil { log.Fatal(err) } defer f.Close() fmt.Fprintln(f, "{{ Quot...
package sort import ( "math/rand" ) // BubbleSort - bubble sort func BubbleSort(a []int) { for range a { for i := len(a) - 1; i > 0; i-- { if a[i-1] > a[i] { a[i-1], a[i] = a[i], a[i-1] } } } } // InsertSort - insert sort func InsertSort(a []int) { for i := 1; i < len(a); i++ { key := a[i] j :=...
package heap import "fmt" type maxHeap struct { Capacity int Array []int } func NewEmptyMaxHeap() Heap { return &maxHeap{ Capacity: 0, Array: make([]int, 0), } } func (h *maxHeap) AddElement(e int) { h.Array = append(h.Array, e) h.Capacity++ j := h.Capacity - 1 for j > 0 { if h.Array[j] > h.Arra...
// 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 catp import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01000102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catp.010.001.02 Document"` Message *ATMPINManagementRequestV02 `xml:"ATMPINMgmtReq"` } func (d *Document01000102)...
package rivescript /* For my own sanity while programming the code, these structs mirror the data in the 'ast' subpackage but uses non-exported fields for the bot's own use. The logic is as follows: - The parser subpackage becomes a stand-alone Go module that third party developers can use to make their own applic...
package handlers import ( "net/http" "github.com/chisty/microservice_go/data" ) // Update handles PUT requests to update products func (p *Products) Update(rw http.ResponseWriter, r *http.Request) { id := getProductId(r) prod := r.Context().Value(KeyProduct{}).(data.Product) err := data.UpdateProd...
package main import ( "fmt" "os" "bufio" "io" "io/ioutil" ) func readFile(path string){ file,err := os.Open(path) if err != nil{ fmt.Printf("read file error\n") return } defer file.Close() inputReader := bufio.NewR...
/* Copyright (C) 2019 by Martin Langlotz aka stackshadow This file is part of gopilot, an rewrite of the copilot-project in go gopilot is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of this Lic...
package ginx import ( "bytes" "encoding/json" "errors" "github.com/spf13/cast" "io/ioutil" ) type IRequest interface { QueryInt(key string, def int) (int, bool) QueryString(key, def string) (string, bool) ParamInt(key string, def int) (int, bool) FormInt(key string, def int) (int, bool) BindJson(obj inte...
package service type QueueReader interface { Consume() (<-chan Event, error) }
package utils import ( "io/ioutil" "net/http" "strconv" "strings" corepb "github.com/projecteru2/core/rpc/gen" "github.com/projecteru2/core/types" "github.com/urfave/cli/v2" ) // ReadAllFiles open each pair in files // and returns a map with key as dstfile, value as linux file // files: list of srcfile:dstfi...
// Copyright 2015 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 dbconnect import ( "fmt" "log" "github.com/hsynakin/GORM/models" "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) var ( appDBName = "gorm" appDBHost = "localhost" appDBUserName = "postgres" appDBPassword = "gorm" DB *gorm.DB ) func Dbase() { cnnString := f...
package controller import ( "encoding/json" "time" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/internal/examples/showcases/wallet/wallet/model" ) var Controller *WalletController type WalletController struct { core.QObject _ func() `constructor:"in...
package cmd import ( "bufio" "encoding/json" "fmt" "net/http" "os" "strings" "github.com/authelia/authelia/v4/internal/utils" ) // Docker a docker object. type Docker struct{} // Build build a docker image. func (d *Docker) Build(tag, dockerfile, target string, buildMetaData *Build) error { args := []string...
// 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 main import ( "encoding/json" "fmt" "strings" "testing" ) // -------- path search func // expect + + + // remember + - + // absent + + - func TestSearch(t *testing.T) { m, err := jsonAsMap( `{ "boo": {"name":"ga-ga"} }`) if err != nil { t.Error(err) } res := Search(m, "boo.name")...
// Copyright 2016 Walter Schulze // // 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...
package heap /* head properties: max-heap: A[parent(i)] >= A[i] min-heap: A[parent(i)] <= A[i] where A is the input data array, i is the index number of A and 0 <= i <= A.length *First, Start with max-heap! Property: height of n nodes complete binary tree = thidta(lg n) */ // floor(i/2) func pare...
package main import "fmt" func main() { for i := 10; i < 101; i++ { fmt.Printf("When %v is diveied by 4 the remainder or the modulus is %v\n", i, i%4) } }