text
stringlengths
11
4.05M
package spec import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" . "test_formats" ) func TestStrEncodings(t *testing.T) { f, err := os.Open("../../src/str_encodings.bin") if err != nil { t.Fatal(err) } s := kaitai.NewStream(f) var h StrEnc...
package conf import ( "fmt" "log" "math/rand" "mi_com_tool_dataset/util" "strconv" "strings" "github.com/Maxgis/tree" "github.com/go-ini/ini" ) var ( Tags = make(map[string]*Group) DEFAULE_TIMEOUT uint64 = 10000 DEFAULT_PROTOCOL = "http" DEFAULT_MAXRETRY uint = 1 ) type Grou...
package logserver import ( "bytes" "net/http" "openRPA-basic-module/models" "io/ioutil" json2 "encoding/json" "strconv" "fmt" "github.com/davecgh/go-spew/spew" "github.com/gin-gonic/gin/json" "github.com/pkg/errors" ) const ( started = "started" processing = "processing" succeeded = "succeeded" ...
package http import ( "time" "net/http" "../../package/db" ) type OutputData struct { Time float64 Path string`json:"Path"` RemoteAddr string //ContentLength int64 Message string Table db.Table } func GetOutputData(req *http.Request)OutputData { outputData := OutputData{} ...
package main import "fmt" func main() { s := []int{6, 8, 30, 2, 30, 7, 8, 7, 7} fmt.Println(maxProfit(s)) } func maxProfit(prices []int) int { n := len(prices) res := 0 for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { if prices[j] > prices[i] { tmp := prices[j] - prices[i] if tmp > res { ...
/* * @file * @copyright defined in aergo/LICENSE.txt */ package p2putil import ( "bytes" "fmt" "github.com/aergoio/aergo/internal/network" "github.com/aergoio/aergo/p2p/p2pcommon" "github.com/aergoio/aergo/types" "github.com/libp2p/go-libp2p-core" "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2...
package main import ( "fmt" hyperclient "github.com/Cloud-Foundations/Dominator/hypervisor/client" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" ) func registerExternalLeasesSubcommand(args []string, logger log.DebugLogger) error { err := registerExternalLea...
package main import ( "log" "net/http" "fmt" "time" "encoding/json" ) //Customer is the data structure that defines a customer type Customer struct { CustID int `json:"cust_id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` CreatedAt time.Time `json:"created_at"` LastLogin time.Tim...
package techpalace import ( "strings" ) // WelcomeMessage returns a welcome message for the customer. func WelcomeMessage(customer string) string { return "Welcome to the Tech Palace, " + strings.ToUpper(customer) } // AddBorder adds a border to a welcome message. func AddBorder(welcomeMsg string, numStarsPerLine ...
/* * @lc app=leetcode.cn id=461 lang=golang * * [461] 汉明距离 */ package main import "fmt" // @lc code=start func hammingDistance(x int, y int) int { res := x ^ y ans := 0 for ; res != 0; res &= res - 1 { ans++ } return ans } // @lc code=end func main() { fmt.Println(hammingDistance(3, 1)) }
/* Given a binary message, and the number of parity bits, generate the associated parity bits. A parity bit is a simple form of error detection. It's generated by counting the number of 1's in the message, if it's even attach a 0 to the end, if it's odd attach 1. That way, if there's a 1-bit error, 3-bit error, 5-bit...
package agent_mgr import ( "github.com/kataras/iris/core/errors" "gosconf" "goslib/gen_server" "goslib/logger" "sync" "time" ) type connectApp struct { Uuid string Host string Port string Ccu int32 CcuMax int32 ActiveAt int64 } type DispatchCache struct { app *connectApp activeA...
package db import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) //MySQLConnect function for connect to mysql func MySQLConnect() (dbs *sql.DB) { dbs, err := sql.Open("mysql", "root@tcp(127.0.0.1:3306)/serviciotest") if err != nil { panic(err.Error()) } return dbs }
package kdtree import "math" type Point interface { Dimensions() int Dimension(i int) float64 } func equals(p1, p2 Point) bool { if p1.Dimensions() != p2.Dimensions() { return false } for i := 0; i < p1.Dimensions(); i++ { if p1.Dimension(i) != p2.Dimension(i) { return false } } return true } func d...
// Copyright (c) 2014 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package walletdb import ( "errors" ) // Errors that can occur during driver registration. var ( // ErrDbTypeRegistered is returned when two different database drivers //...
// Copyright 2022 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 logger handles application logging */ package logger import ( "context" "errors" "fmt" "github.com/sirupsen/logrus" "net/url" "os" "strings" ) const ( // TraceLevel represents the TRACE logging level TraceLevel = "trace" // DebugLevel represents the DEBUG logging level DebugLevel = "debug" // I...
package main import ( "crypto/tls" "log" "net" "time" "gopkg.in/mgo.v2" ) var dbSession *mgo.Session var db *mgo.Database // initDb initialises the dbSession and db variables with a new mongodb session and the default database func initDb() (err error) { var dbInfo = &mgo.DialInfo{ Addrs: config.DB...
package schema import ( "crypto/tls" "net/mail" "net/url" "time" ) // Notifier represents the configuration of the notifier to use when sending notifications to users. type Notifier struct { DisableStartupCheck bool `koanf:"disable_startup_check" json:"disable_startup_check" jsonschema:"default=fa...
package graphicgo import ( "errors" ) const ( Slim = iota Middle Bold ) func abs(x int64) (abs int64) { if x > 0 { return x } else { return -x } } func DrawDot(x int64, y int64, color [4]byte, width int) (err error) { if width == Slim { dot(x, y, color) } else if width == Middle { dot(x-1, y, color...
//sandbox is command line interface for the Sandbox without docker wrapped. // Example: // compile before running // sandbox --lang=c -c -s src/main.c -b bin/main --memory=10000 --time=1000 --input=judge/input --output==judge/output // running without compiling // sandbox --lang=c -b bin/ma...
package build import ( "context" "fmt" "os" "os/exec" "path/filepath" "reflect" "sort" "strconv" "strings" "github.com/pkg/errors" "github.com/outofforest/ioc/v2" "github.com/outofforest/libexec" "github.com/outofforest/logger" "github.com/outofforest/run" "github.com/ridge/must" ) const maxStack = 1...
package types import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) var ( ErrInvalidBasicMsg = sdkerrors.Register(ModuleName, 1, "InvalidBasicMsg") ErrBadDataValue = sdkerrors.Register(ModuleName, 2, "BadDataValue") ErrUnauthorizedPermission = sdkerrors.Register(ModuleName, 3, "Unautho...
package ssh import ( "bufio" "errors" "net" "os" "time" gossh "github.com/coreos/fleet/third_party/code.google.com/p/go.crypto/ssh" "github.com/coreos/fleet/third_party/code.google.com/p/go.crypto/ssh/terminal" ) func Execute(client *gossh.ClientConn, cmd string) (*bufio.Reader, error) { session, err := clie...
package main import ( "KServer/manage" "KServer/manage/config" "KServer/server/lock/services" "KServer/server/utils" "KServer/server/utils/msg" "fmt" ) func main() { mConf := config.NewManageConfig() mConf.DB.Redis = true mConf.Server.Head = msg.LockTopic mConf.Message.Kafka = true mConf.Lock.Open = true...
package main import ( "os" "fmt" "io" ) func main() { CopyFile() } func CopyFile() { copyFile("output.txt", "outputCpy.txt") fmt.Println("copy done!") } func copyFile(srcName, dstName string) (written int64, err error) { srcFile, err := os.Open(srcName) if err != nil { fmt.Println("open src file err:", e...
package main import ( "fmt" "sort" "golang.org/x/exp/constraints" ) // Map turns a []T1 to a []T2 using a mapping function. // This function has two type parameters, T1 and T2. // This works with slices of any type. func Map[T1, T2 any](s []T1, f func(T1) T2) []T2 { r := make([]T2, len(s)) for i, v := range s ...
package gcalbot import ( "bytes" "crypto/hmac" "encoding/base64" "fmt" "io" "net/http" "strconv" "strings" "time" "google.golang.org/api/googleapi" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat" "github.com/malware-unicorn/man...
package aoc2020 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_readBoardingPass(t *testing.T) { assert := assert.New(t) // use example board passes testCases := []struct { input string seat planeSeat seatID int }{ {"FBFBBFFRLR", planeSea...
package datatransformer import ( "sync" "time" "github.com/google/uuid" ) type DataTransformerManager struct { sync.Mutex instances map[uuid.UUID]*DataTransformer } func (d *DataTransformerManager) NewTransformer() uuid.UUID { d.Lock() defer d.Unlock() id := uuid.New() d.instances[id] = &...
package examples import ( "encoding/json" "fmt" ) type user struct { Id int `json:"id"` Name string `json:"name"` City city `json:"city"` } type city struct { Id int `json:"id"` Name string `json:"name"` } var userJohn = user{ Id: 1, Name: "John", City: city{ Id: 3, Name: "London", },...
package util import ( "os" ) // DirExists checks if the path exists and is a directory func DirExists(path string) (bool, error) { info, err := os.Stat(path) if err == nil { return info.IsDir(), nil } else if os.IsNotExist(err) { return false, nil } return false, err } // MkdirAll creates a directory named...
package main import ( "fmt" "math/rand" "time" ) func main() { fmt.Println("Hello, world!") rand.Seed(time.Now().Unix()) // set numbers numbers := [5]int{rand.Intn(10), rand.Intn(10), rand.Intn(10), rand.Intn(10), rand.Intn(10)} fmt.Println(numbers) sort(numbers[:]) } func sort(numbers []int) { // var for ...
package ipam import ( "context" "encoding/json" "fmt" "math/bits" "math/rand" "net" "sort" "sync" "time" g8sv1alpha1 "github.com/giantswarm/apiextensions/pkg/apis/cluster/v1alpha1" "github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1" "github.com/giantswarm/apiextensions/pkg/clientset/versioned...
package game import ( "github.com/tanema/amore" "github.com/tanema/amore/keyboard" ) // World encapsulates the whole environment type World struct { size int terrain [][]*Cell camera *Camera timeOfDay float32 sin float32 sky *Sky player *Voxel } const ( worldSaturation float32 = 0...
package totp import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/binary" "fmt" "hash" "time" ) const ( VERSION = "1.0.0" ) type Token struct { key []byte epoch time.Time interval time.Duration hash func() hash.Hash } func New(key []byte) Token { token := Token{ key: key, epoch...
package app import ( "bytes" "fmt" "os/exec" "strings" ) type Error interface { Error() string } func ExtractVideoDevices() ([]string, Error) { cmd := exec.Command("imagesnap", "-l") var out bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr err := cmd.Run() if err != nil { fmt...
package main import ( "context" "errors" "fmt" "io" "os" "github.com/werf/werf/pkg/docker" "github.com/werf/werf/pkg/util" "github.com/werf/werf/pkg/buildah" "github.com/werf/werf/pkg/werf" ) var errUsage = errors.New("./buildah-test {auto|native-rootless|docker-with-fuse} DOCKERFILE_PATH [CONTEXT_PATH]")...
package main import ( "strconv" "fmt" ) // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root)); const ( PlaceHolder = "#" Delimiter = "|" ) type TreeNode struct{ Val int Left *TreeNode Right *TreeNode } func serialize(root *TreeNode) string{...
// time: O(n), space: O(n) func spiralOrder(matrix [][]int) []int { visited := make([][]int, len(matrix)) for i := 0; i < len(matrix); i++ { visited[i] = make([]int, len(matrix[0])) } dirs := [][]int{[]int{0, 1}, []int{1, 0}, []int{0, -1}, []int{-1, 0}} curDir := 0 curX, curY := 0, 0 ...
package sudoku import ( "testing" ) func TestSubsetCellsWithNUniquePossibilities(t *testing.T) { grid := NewGrid() grid, err := MutableLoadSDKFromFile(puzzlePath("hiddenpair1_filled.sdk")) if err != nil { t.Log("Failed to load hiddenpair1_filled.sdk") t.Fail() } cells, nums := subsetCellsWithNUniquePossib...
package api import ( "encoding/json" "io/ioutil" "github.com/enjoy-web/ehttp" "github.com/enjoy-web/ehttp/examples/restful-demo/model" "github.com/gin-gonic/gin" ) var DocPostBook = &ehttp.APIDocCommon{ Summary: "new a book", Produces: []string{ehttp.Application_Json}, Consumes: []string{ehttp.Application_J...
package main import ( "fmt" "time" ) /* reference: https://docs.studygolang.com/pkg/time/ */ /* go 语言 time.go 时间库 常用的一些方法 //1、Now()返回当前本地时间 //2、Local()将时间转成本地时区,但指向同一时间点的Time。 //3、UTC()将时间转成UTC和零时区,但指向同一时间点的Time。 //4、Date()可以根据指定数值,返回一个本地或国际标准的时间格式。 //5、Parse()能将一个格式化的时间字符串解析成它所代表的时间。就是string转time //6、Forma...
package model import ( "github.com/go-xorm/xorm" ) var ( initUserSql = `INSERT INTO user (address) VALUES (?)` ) // Init user information, func initUser(session *xorm.Session, userAddress string) (int64, error) { // Execute SQL. r, err := session.Exec(initUserSql, userAddress) if err != nil { return 0, err }...
package main import ( "fmt" "github.com/Cloud-Foundations/Dominator/dom/lib" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" ) func fetchImageSubcommand(args []string, logger log.DebugLogger) error { startTime := showStart("getSubClient()") srpcClient := getSu...
package BLC import ( "bytes" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "fmt" ripemd1602 "golang.org/x/crypto/ripemd160" "log" ) const version = byte(0x00) const addressCHecksumLen = 4 type Wallet struct { // 1.私钥 PrivateKey ecdsa.PrivateKey // 2.公钥(私钥生成的公钥) PublicKey []byte } //创建钱包...
package main import ( "fmt" "strings" "strconv" ) func main() { s := "hello world" fmt.Println(strings.Contains(s, "hello"), strings.Contains(s, "?")) fmt.Println(strings.Index(s, "o")) ss := "1#2#345" splitedStr := strings.Split(ss, "#") fmt.Println(splitedStr) fmt.Println(strings.Join(splitedStr, "#")) ...
package linkedstack import ( "sync" ) //node the type of the LinkedStack, actually it's a node of linkedlist type node struct { value interface{} next *node } //LinkedStack the structure of LinkedStack type LinkedStack struct { length int lock *sync.RWMutex next *node } //NewLinkedStack creates a new Lin...
package orderagregate //Order agregate root for the order domain type Order struct { ID string `json:"id,omitempty" bson:"_id,omitempty"` OrderItems []OrderItem `json:"orderItems" bson:"order_items"` Status string `json:"status" bson:"status"` } //CreateOrder order func CreateOrder(orderItem ...
package leclog import ( "fmt" "log" "time" ) type timeOnlyLogWriter struct { } func (writer timeOnlyLogWriter) Write(bytes []byte) (int, error) { return fmt.Print(time.Now().Format("15:04:05") + " " + string(bytes)) } type Pattern int const ( TimeOnly Pattern = iota ) func SetLogPattern(pattern Pattern) { s...
package main import ( "bytes" "testing" "github.com/mumoshu/gosh" "github.com/mumoshu/gosh/goshtest" "github.com/stretchr/testify/assert" ) func TestMain(t *testing.T) { sh := New() goshtest.Run(t, sh, func() { t.Run("foo", func(t *testing.T) { var stdout bytes.Buffer err := sh.Run(t, "foo", "a", "b...
package main import "fmt" func main() { nums := []int{0, 1, 0, 1, 0, 1, 99} fmt.Println(singleNumber(nums)) } func singleNumber(nums []int) int { x, y := 0, 0 for _, v := range nums { y = ^x & (y ^ v) x = ^y & (x ^ v) } return y }
package usecases import ( "persons.com/api/domain/person" ) type PersonUseCases interface { FindById(id string) (*person.Person, error) GetAll() ([]*person.Person, error) Create(person *person.Person) error } //cache service port type PersonsCacheService interface { Set(key string, person *person.Person) error ...
// Copyright © 2016 Kim Eik // // 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, modify, merge, publish, distrib...
/* Given a unordered array of the vertices of a convex polygon, find its area. Examples polygon([[2, 5], [5, 1], [-4, 3]]) ➞ 15.0 polygon([[-1, 1], [1, 1], [-1, -1], [1, -1]]) ➞ 4.0 polygon([[2, 2], [11, 2], [4, 10], [9, 7]]) ➞ 45.5 polygon([[5, 3], [3, 4], [12, 8], [5, 11], [9, 5]]) ➞ 39.0 Notes A convex p...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package main import ( "fmt" ) //函数,返回值可以有多个,go语言中没有默认参数这个概念,要么传参数要么不传参数 //可以在函数里直接使用命名返回值,就是在声明函数的时候已经给函数命名了 func test(a int)(b int){ b=a return b //这里也可以直接写return就可以,如果不是命名那么就不可以直接return,一定要写返回的具体的返回值 } //参数中如果两个连续的变量类型一样那么我们可以将前面的那个参数类型省略 func test2(a,b int)(int,int){ return a,b } //可变长参数 ,这里y类型是切片,可以传也可以不传,...
package cmd import ( "os" "github.com/spf13/cobra" "github.com/Zenika/marcel/config" "github.com/Zenika/marcel/frontend" ) func init() { var cfg = config.New() var cmd = &cobra.Command{ Use: "frontend", Short: "Starts Marcel's Frontend server", Args: cobra.NoArgs, PreRunE: preRunForServer(cfg), ...
package main import "net" var c net.Conn var e error // func main() { // c, e = net.Dial("tcp", "localhost:5555") // if e != nil { // panic(e) // } // i := 0 // for { // _, err := c.Write([]byte("hi" + strconv.Itoa(i) + "\n")) // if err != nil { // println(err) // } // // time.Sleep(1e9) // buf :...
package main func totalNQueens(n int) int { res := 0 //每一列是否被占用 col := make([]bool, n) //左对角线是否有元素 dia1 := make([]bool, 2*n-1) //因为有2*n-1条对角线 //右对角线是否有元素 dia2 := make([]bool, 2*n-1) //因为有2*n-1条对角线 var putQueen func(int, int) putQueen = func(index int, n int) { //index代表当前处理的行,n是问题规模,row代表第 if index == n { /...
package main import ( "context" "flag" "fmt" "log" "strings" multiaddr "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr" quic "gx/ipfs/QmPxDT1mJcdVbPSGRrActszXdptSgcj9gtyMuhrPavXFCN/go-libp2p-quic-transport" relay "gx/ipfs/QmQG8wJtY6KfsTH2tjhaThFPeYVJGm7cmRMxen73ipA4Z5/go-libp2p-circuit" ...
package main import ( "fmt" "sort" ) //给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。 //请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。 //输入:nums = [4,3,2,7,8,2,3,1] //输出:[5,6] func main() { fmt.Println(findDisappearedNumbers([]int{4, 3, 2, 7, 8, 2, 3, 1})) } func findDisappearedNumbers(nums []int) []int { so...
// Package queue defines queue constants. package queue import ( "encoding/json" "fmt" "strings" ) type Queue int func (q *Queue) UnmarshalJSON(b []byte) error { var ( s string i int ) // First see if it is stored as native int. err := json.Unmarshal(b, &i) if err == nil { *q = Queue(i) return nil ...
package random import ( "math/rand" ) // New returns a new random string with a number of characters defined by // the function parameter `length` and, eventually, some special chars // and digits, depending on whether `specialChars` and/or `digits` are `true` func New(length int, specialChars, digits bool) string {...
package leetcode func LongestValidParentheses(s string) int { llnum, lrnum, rlnum, rrnum := 0, 0, 0, 0 max := 0 length := len(s) - 1 for i := 0; i <= length; i++ { if s[i] == 40 { llnum++ } if s[i] == 41 { lrnum++ } if s[length-i] == 40 { rlnum++ } if s[length-i] == 41 { rrnum++ } if ...
package main import ( "testing" ) func TestSingleNumber(t *testing.T) { }
package models import ( "github.com/astaxie/beego/orm" "time" ) //查询的类 type HashrateOrderTransactionQueryParam struct { BaseQueryParam Name string `json:"name"` StartTime int64 `json:"startTime"` //开始时间 EndTime int64 `json:"endTime"` //截止时间 Status string `json:"status"` //状态 } func (a *Hashra...
// Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package views import ( "net/http" "strings" ) // HTTPHandler ! func HTTPHandler(w http.ResponseWriter, r *http.Request) { // r.URL.Path creates a new path called /http_handler r.URL.Path = strings.TrimPrefix(r.URL.Path, "/http_handler") if strings.HasPrefix(r.URL.Path, "/todo") { TodoHandler(w, r) return }...
package priorityqueue import ( "LimitGo/limit/collection" "testing" ) var precede = func(p1 *collection.Object, p2 *collection.Object) bool { s1 := (*p1).(Student) s2 := (*p2).(Student) return s1.Id < s2.Id } type Student struct { Id int Name string } func TestArrayListAll(t *testing.T) { TestNew(t) TestPr...
package backend // OpenSentencer represents an interface where a fetch on an opeing sentence is made. type OpenSentencer interface { OpenSentence() (string, error) }
/* * @lc app=leetcode id=13 lang=golang * * [13] Roman to Integer */ package main /* Solution 1: */ func romanToInt(s string) int { res := 0 mapping := [128]int{} mapping['I'] = 1 mapping['V'] = 5 mapping['X'] = 10 mapping['L'] = 50 mapping['C'] = 100 mapping['D'] = 500 mapping['M'] = 1000 for i := 0; i ...
package compute import ( "encoding/json" "fmt" "log" "net/http" "net/url" ) // IPAddressList represents an IP address list. type IPAddressList struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` IPVersion ...
package 一维数组 // firstMissingPositive 找到数组中第一个缺失的正数。 func firstMissingPositive(nums []int) int { // 1. 让正数占领 nums[正数-1] 的位置。 (比如正数 1、2、3,分别占领 nums[0]、nums[1]、nums[2]) // (比如正数 1、2、3,分别占领 nums[0]、nums[1]、nums[2]) for i := 0; i < len(nums); i++ { for nums[i] >= 1 && nums[i] <= len(nums) && nums[i] != i+1 && nums[num...
package processor import ( "github.com/bitmaelum/bitmaelum-suite/internal/message" "github.com/sirupsen/logrus" "time" ) const ( // MaxRetries defines how many retries we can do for sending a message MaxRetries int = 30 ) // ProcessRetryQueue will process all mails found in the retry queue or removes them when ...
package main import ( "net" "log" "github.com/gobwas/ws" ) func main() { ln, err := net.Listen("tcp", "localhost:9999") if err != nil { log.Fatal(err) } u := ws.Upgrader{ OnHeader: func(key, value []byte) (err error) { log.Printf("non-websocket header: %q=%q", key, value) return }, } for { conn...
package rest import ( "encoding/json" "fmt" "log" "net/http" ) func RespOk(w http.ResponseWriter, message string, data map[string]interface{}) { w.Header().Add("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(200) resp := Response{ Status: 200, Message: message, Data: data, } body...
package main import "fmt" type Node struct { data int next *Node } func NewNode(v int) *Node { var n Node n.data = v n.next = nil return &n } func PrintList(n *Node) { t := n for t != nil { fmt.Println(t.data) t = t.next } } func Reverse(n *Node) *Node { var curr *Node var ...
package main import "fmt" func main() { var n int32 fmt.Scanf("%d", &n) s := fmt.Sprintf("%b", n) max := 0 count := 0 for _, r := range s { if fmt.Sprintf("%s", string(r)) == "1" { count++ } else { count = 0 } if count > max { max = count } } fmt.Println(max) }
// +build qml package detail import ( "github.com/therecipe/qt/quick" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/controller" ) func init() { detailController_QmlRegisterType2("Detail", 1, 0, "DetailController") } type detailController struct { quick.QQuickItem _ func() `...
package main import ( "encoding/json" "fmt" "github.com/gomodule/redigo/redis" "log" "net/http" "strings" "time" ) type ReturnResult struct { Success bool Content string } func sayHello(w http.ResponseWriter, r *http.Request){ r.ParseForm() for k,v := range r.Form{ fmt.Println("key", k) fmt.Println("val...
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package upgrader import ( "log" "github.com/hashicorp/go-multierror" corev1 "k8s.io/api/core/v1" ) type Concurr...
package mytls import ( "crypto/tls" "crypto/x509" "errors" "google.golang.org/grpc/credentials" "io/ioutil" "log" "strings" ) func GetTLSCreds(certFile, keyFile, caDir string, isServer bool) (credentials.TransportCredentials, error) { if !strings.HasSuffix(caDir, "/") { caDir += "/" } cert, err := tls.Loa...
package registerpeserta import ( "context" "github.com/mirzaakhena/danarisan/domain/entity" "github.com/mirzaakhena/danarisan/domain/service" "github.com/mirzaakhena/danarisan/usecase/registerpeserta/port" "strings" ) //go:generate mockery --dir port/ --name RegisterPesertaOutport -output mocks/ type registerPe...
package 字符串 import ( "bytes" "sort" ) // -------------- 不使用任何数据结构的版本 -------------- func isUnique(astr string) bool { for i:=0;i<len(astr);i++{ for t:=i+1;t<len(astr);t++{ if astr[i]==astr[t]{ return false } } } return true } func isUnique(astr string) bool { for i:=0;i<len(astr);i++{ if bytes....
package main import "fmt" func main() { const distance = 236000000000000000 const lightSpeed = 299792 const secondsPerDay = 86400 const daysPerYear = 365 lightYears := distance / lightSpeed / secondsPerDay / daysPerYear fmt.Println(lightYears) }
package compiler import ( "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" ) type fsLoader struct { *Repository abspath string } func (l *fsLoader) findGrammars() (files []string, err error) { err = filepath.Walk(l.abspath, func(path string, info os.FileInfo, err error) error { if err == nil...
package intermediate // All of the formats specified above are available here. It is expected that implementations use this wherever // possible to allow for changes const ( Sentinel = '$' Bold = 'b' Italic = 'i' Underline = 'u' Strikethrough = 's' Reset = 'r' Colour = 'c...
package main import ( "github.com/kaleido-io/kaleido-sdk-go/cmd" ) func main() { cmd.Execute() }
package main import ( "fmt" "short-url/server" ) func main() { // uncomment the following lines for a persistent data store (BoltDB). // Note: I'm setting a global variable which is very bad. Again, just a quick and dirty implementation. // There is a known bug with the `Visits` and the persistent store. It alwa...
package hcledit_test import ( "fmt" "strings" "go.mercari.io/hcledit" ) func Example() { src := ` resource "google_container_node_pool" "nodes1" { name = "nodes1" node_config { preemptible = false machine_type = "e2-medium" } timeouts { create = "30m" } } resource "google_container_node...
package webhook import ( "bytes" "crypto/hmac" "crypto/sha1" "encoding/json" "fmt" "hooksim/config" "hooksim/types" "io/ioutil" "log" "net/http" "github.com/satori/go.uuid" ) var ( // For constructing the repository json object with the same field order as github's output repoFields = [...]string{"id", ...
//Package binarysearchtree 实现了二叉搜索树数据结构 package binarybalancetree import ( "container/list" "reflect" ) //Item:树节点的数据可以是任意类型 type Item interface{} //TreeNode:结点结构 type TreeNode struct { Val int Height int Left *TreeNode Right *TreeNode } type LevelOrder struct { Val int Height int } //将传入数组转换成二叉树 ...
package main import "fmt" // 1. To satisfy an interface you have to use methods not func // 2. Create methods with exact same signature as of in interface // 3. Create all methods in struct as specified in interface. Or your struct should satisfy all of the methods of an interface type Shape interface { Area() floa...
package nv4 import ( "context" address "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" power0 "github.com/filecoin-project/specs-actors/actors/builtin...
package constants import "path/filepath" const ( OcBinaryName = "oc" TrayBinaryName = "CodeReady Containers.app" ) var ( TrayBinaryPath = filepath.Join(CrcBinDir, TrayBinaryName) )
package main import ( "strconv" "github.com/gin-gonic/gin" "github.com/rossifedericoe/bootcamp/apirest/dto" "github.com/rossifedericoe/bootcamp/apirest/services/movieService" ) func main() { engine := gin.Default() engine.GET("/movies", func(context *gin.Context) { context.JSON(200, movieService.ListarMovie...
package mytest import ( "fmt" "reflect" "strconv" "testing" "time" ) type PaymentInfoResponse struct { MsgID string `json:"msg_id"` CardNumber string `json:"card_number"` } func TestFiledName(t *testing.T) { p := &PaymentInfoResponse{} typ := reflect.TypeOf(p) elem := typ.Elem() totalFields := elem.N...
package sessions_test import ( "crypto/rand" "encoding/hex" "net/http" "net/http/httptest" "sync" "testing" "time" "github.com/go-http-utils/cookie" "github.com/go-http-utils/cookie-session" "github.com/stretchr/testify/assert" ) var ( username = "mushroom" useage int64 = 99 ...
package main import ( "fmt" "io/ioutil" "log" "os" cli "github.com/jawher/mow.cli" "github.com/karantin2020/gitcomm" "github.com/karantin2020/gitcomm/version" ) func main() { app := cli.App("gitcomm", "Automate git commit messaging\n"+ "\nSource https://github.com/karantin2020/gitcomm") app.Version("V ver...