text
stringlengths
11
4.05M
package examples import ( "fmt" "strconv" ) func convert() { s := strconv.Itoa(34) fmt.Print(s) if s, err := strconv.Atoi(s); err != nil { fmt.Print(s) } }
package printer import ( "fmt" "io" ) // DebugPrinter wraps a Printer with debug messages type DebugPrinter struct { P Printer } func (d *DebugPrinter) Reset() { d.P.Reset() } func (d *DebugPrinter) PushContext(c ContextType) { d.P.PushContext(c) } func (d *DebugPrinter) PopContext() { d.P.PopContext() } fu...
package robot import ( "github.com/gin-gonic/gin" "github.com/grearter/rpa-agent/util" "github.com/sirupsen/logrus" "net/http" ) // Delete 删除/停止机器人 func Delete(c *gin.Context) { robotID := c.Param("robotId") logrus.Infof("stop robot '%s' success", robotID) c.JSON(http.StatusOK, util.NewRespWithData(nil)) re...
package walletrpcclient import ( "bytes" "context" "fmt" "io" "sort" "github.com/decred/dcrd/chaincfg/chainhash" "github.com/decred/dcrd/dcrutil" "github.com/decred/dcrd/wire" pb "github.com/decred/dcrwallet/rpc/walletrpc" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/raedahgr...
package goroutines import ( "fmt" "time" ) func run() { for i := 0; i < 5; i++ { fmt.Println("i is ", i) } } func greeting() { fmt.Println("Hello") } // Init init func Init() { go run() // pushed to the stack go greeting() // pushed to the stack // greeting get popped first // run get's popped last...
package fakes import ( "errors" "github.com/cloudfoundry-incubator/notifications/web/services" ) type FakePreferencesFinder struct { ReturnValue services.PreferencesBuilder FindErrors bool UserGUID string } func NewFakePreferencesFinder(returnValue services.PreferencesBuilder) *FakePreferenc...
package main func dfs(node int, nodes map[int][]int, fn func (int)) { dfs_recur(node, map[int]bool{}, fn) } func dfs_recur(node int, v map[int]bool, fn func (int)) { v[node] = true fn(node) for _, n := range nodes[node] { if _, ok := v[n]; !ok { dfs_recur(n, v, fn) } } ...
package main import ( "math" ) func main() { const n = 500000000 const d = 3e20 / n println(d) println(int64(d)) println(math.Sin(180)) }
package server import ( "time" ) type TimeInfo struct { FrameCount int RunTime time.Duration //总运行时间 StartTime time.Time //开始运行时间 DeltaTime time.Duration //update间隔照章 LastUpdateTime time.Time //最后一次更新时间 LastBeatTime time.Time //最后一次心跳时间 LastScanTime time.Time //最后一次扫描时...
// Copyright (c) 2017-2018 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 package zedagent // cipher specific parser/utility routines import ( "bytes" "crypto/sha256" "errors" "fmt" "io/ioutil" zconfig "github.com/lf-edge/eve/api/go/config" "github.com/lf-edge/eve/pkg/pillar/types" log "github.com/siru...
func flipAndInvertImage(A [][]int) [][]int { var n = len(A) if n == 0 { return A } var m = len(A[0]) for i := 0; i < n; i++ { for j := 0; j << 1 < m; j++ { var t = A[i][j] A[i][j] = 1 - A[i][m - j - 1] A[i][m - j - 1] = 1 - t } } return A }
package timewheel type Chunk struct { id int32 used int32 prev int32 next int32 data TimeWheelTaskData } type TimeWheelAllocator struct { capacity int32 size int32 freeHead int32 Chunks []Chunk stat TimeWheelAllocatorStat } type TimeWheelAllocatorStat struct { Alloc uint64 AllocOk uint64 F...
// Package parser is used to parse input-programs written in monkey // and convert them to an abstract-syntax tree. package parser import ( "fmt" "strconv" "strings" "github.com/kasworld/nonkey/enum/precedence" "github.com/kasworld/nonkey/enum/tokentype" "github.com/kasworld/nonkey/interpreter/ast" "github.com...
package main import ( "flag" "fmt" "io/ioutil" "log" "os" "path/filepath" "encoding/json" "github.com/OpenDataHH/BetBerichtCreateJSON/pdb" gobeteiligungsbericht "github.com/OpenDataHH/GoBeteiligungsbericht" ) func main() { xmlFile := flag.String("file", "", "XML Datei Beteiligungsbericht HH") outFolder :...
package encryptor import ( "crypto/aes" "encoding/base64" "errors" "github.com/mukesh0513/RxSecure/internal/utils" "github.com/sirupsen/logrus" ) func EcbEncrypt(key []byte, message string) (string, error) { plaintext := utils.PKCS5Padding([]byte(message), aes.BlockSize) if len(plaintext)%aes.BlockSize != 0 ...
package docker_registry import ( "context" "fmt" "net/url" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/werf/werf/pkg/docker" "github.com/werf/werf/pkg/image" ) type genericApi struct { commonApi *api mirrors []string } func newGenericA...
package main import ( "flag" "fmt" "os" "os/exec" "sync" ) var parallel bool var count int func init() { flag.IntVar(&count, "n", 10, "启动的容器数量") flag.BoolVar(&parallel, "p", false, "并发启动") } func runContainer() { cmd := exec.Command("python3", "./core.py") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if...
package main import ( "net/http" "github.com/gin-gonic/gin" ) // webServer func webServer() { r := gin.Default() v2 := r.Group("v2") v2.GET("/home", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "Home", }) }) // /login v2.POST("/login", func(c *gin.Context) { username := c.PostForm...
package concatenate func Concatenate(x, y string) (string, string) { return "", x + y } func Calladd(x, y int) int { return add(x, y) }
package auth import ( "errors" "log" "net/http" "os" "strconv" "time" "github.com/SermoDigital/jose/crypto" "github.com/SermoDigital/jose/jws" "github.com/SermoDigital/jose/jwt" ) // CreateJWT returns a JWT given a valid userid+password func CreateJWT(username string) ([]byte, error) { var err error sign...
package main import ( "testing" "github.com/stretchr/testify/assert" ) func Test_isInChans(t *testing.T) { tests := map[string]struct { all []string sparse []string want []string }{ "should return a slice with true or false emojis": { all: []string{"a", "b", "c", "d"}, sparse: []string{"a",...
package controller import ( "github.com/kataras/iris/context" "go-mysql/customlogger" "go-mysql/model" "go-mysql/router" ) func init () { c := router.CreateNewControllerInstance("clear", "/health") c.Get("", checkHealth) } func checkHealth (ctx context.Context) { logger := customlogger.GetInstance() logger.P...
package washoe import () type Street struct { Full string Number int Fraction string Prefix string Street string Type string Suffix string } func (street *Street) String() string { return street.Full }
package credential import "github.com/appootb/substratum/credential" func Init() { if credential.ClientImplementor() == nil { credential.RegisterClientImplementor(&ClientSeed{}) } if credential.ServerImplementor() == nil { credential.RegisterServerImplementor(&ServerSeed{}) } }
package echo import ( "net/http" "testing" "github.com/GoAdminGroup/go-admin/tests/common" "github.com/gavv/httpexpect" ) func TestEcho(t *testing.T) { common.ExtraTest(httpexpect.WithConfig(httpexpect.Config{ Client: &http.Client{ Transport: httpexpect.NewBinder(internalHandler()), Jar: httpexpec...
package main import ( "flag" "fmt" "github.com/joho/godotenv" "goapigen/genjson" "goapigen/genstruct" "os" ) //Program to reverse engineer your mysql database into gorm models func main() { godotenv.Load(os.Getenv("PWD") + "/.env") user := os.Getenv("DB_USERNAME") pass := os.Getenv("DB_PASSWORD") host := os...
package vericomp import ( "fmt" "io" "bytes" "math/big" "strconv" "log" "os" "unicode" "vericomp/util" ) const FIELD_BITS = 128 // Terms type term struct { coef interface{} variable string } func t(variable string) term { return ti(1, variable) } func tn(variable ...
package models import ( "github.com/nsqio/go-nsq" "time" ) // IngestState stores information about the state of ingest operations // for a single bag being ingested into APTrust. The ingest process involves // a number of steps and worker processes. This state object is passed from // one worker to the next, and ac...
package provider import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "path" "strings" ) var DefaultPath = "/usr/local/lib/summon" // Resolve resolves a filepath to a provider // Checks the CLI arg, environment and then default path func Resolve(providerArg string) (string, error) { provider := providerArg if...
package lexer import ( "theduke/token" "unicode/utf8" "unicode" ) type Lexer struct { input string position int // current position in input readPosition int // current reading position in input ch rune // current char under examination } func New(input string) *Lexer { l := &Lexer{input: input} l.r...
package libserver import ( "bytes" "context" "crypto/tls" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "os/signal" "strconv" "strings" "time" "github.com/helloferdie/stdgo/libserver/claim" "github.com/helloferdie/stdgo/libresponse" "github.com/helloferdie/stdgo/libslice" "github.com/helloferdie/...
package _114_Flatten_Binary_Tree_to_Linked_List type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func flatten(root *TreeNode) { //flattenRecursion(root) flattenIteration(root) } func flattenIteration(root *TreeNode) { cur := root for cur != nil { lp := cur.Left if cur.Left != nil { fo...
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
package client import ( "context" "fmt" "io" "strings" "github.com/wish/ctl/pkg/client/logsync" v1 "k8s.io/api/core/v1" "k8s.io/client-go/rest" ) // LogPodOverContexts retrieves logs of a single pod (uses first found if multiple) func (c *Client) LogPodOverContexts(contexts []string, namespace, name, containe...
package main import "fmt" type MobileAlertState interface { alert() } type AlertStateContext struct { currentState MobileAlertState } func NewAlertStateContext() *AlertStateContext { return &AlertStateContext{currentState: &Vibration{}} } func (ctx *AlertStateContext) SetState(state MobileAlertState) { ctx.cur...
// This file was generated for SObject UserAppMenuItem, API Version v43.0 at 2018-07-30 03:47:34.623499103 -0400 EDT m=+20.966892275 package sobjects import ( "fmt" "strings" ) type UserAppMenuItem struct { BaseSObject AppMenuItemId string `force:",omitempty"` ApplicationId string `force...
package oss // CreateObject is func (t *Oss) CreateObject() { } // DeleteObject is func (t *Oss) DeleteObject() { } // UpdateObject is func (t *Oss) UpdateObject() { } // GetObject is func (t *Oss) GetObject() { }
package metadata import ( "incognito-chain/common" ) type PDEContributionResponse struct { MetadataBase ContributionStatus string RequestedTxID common.Hash TokenIDStr string SharedRandom []byte } func NewPDEContributionResponse( contributionStatus string, requestedTxID common.Hash, tokenI...
package server import ( "bloom-clock/operations" "encoding/json" "fmt" "io/ioutil" "log" "net" "strconv" "github.com/spencerkimball/cbfilter" ) type Message struct { From int To int Type string Element string BloomClock []byte Broadcast bool } var neighborNodes []int func Clie...
package 数组 var diagonalsOwningSameHash map[float64][]*Diagonal const INF = 100000000000000.0 func minAreaFreeRect(points [][]int) float64 { diagonalsOwningSameHash = make(map[float64][]*Diagonal) coordinates := make([]*Coordinate, 0) diagonals := make([]*Diagonal, 0) minArea := INF for _, point := range points ...
package calendar import ( "strconv" "strings" "time" "github.com/kudrykv/latex-yearly-planner/app/components/hyper" ) type Calendar struct { wd time.Weekday weeks Weeklies month time.Month } func (c Calendar) WeekLayout(weekNum bool) string { line := strings.Repeat("c", 7) if !weekNum { return line }...
package payment type CreditAccount struct { accountNumber string accountOwner string } func (c CreditAccount) AccountNumber() string { return c.accountNumber } func (c CreditAccount) AccountOwner() string { return c.accountOwner } func (c CreditAccount) AvailableCredit() float32 { return 1000 }
// Copyright 2016-2019 Authors of Cilium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
// +build integration package main import ( "context" "crypto/sha256" "fmt" "log" "os" "sync" "github.com/Azure/go-autorest/autorest/azure/auth" "github.com/osbuild/osbuild-composer/internal/boot/azuretest" "github.com/osbuild/osbuild-composer/internal/cloud/gcp" "github.com/osbuild/osbuild-composer/inter...
package rotationfile import ( // "fmt" "os" "strings" "sync" "time" ) type Rotator struct { baseFileName string currentFileName string internalFile *os.File rotationByTime int nextRotationTime int64 fileLock sync.Mutex } func (this *Rotator) GetCurrentFileName() string { return this.c...
// 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 services import ( "context" "encoding/json" "errors" "fmt" "goChat/Server/db" "goChat/Server/models" "goChat/Server/utils" "log" "net/http" "strings" "time" "github.com/dgrijalva/jwt-go" ) const signingKey = "APIKeyWHICHISNotTOOSECRET" var keyGetter = func(t *jwt.Token) (interface{}, error) { r...
/* FOR EXPERIMENTATION ONLY the os pkg (and even os/exec) are better suited for low-level stuff, in comparison to Lua's os library */ package main import ( "os/exec" "io" //"os" //"encoding/json" //"strings" "fmt" ) func PathCheck(bin ...string) bool { valid := ...
package router import ( "net/http" "strconv" "github.com/mrap/combo/functions/api/models" "github.com/gin-gonic/gin" eztemplate "github.com/michelloworld/ez-gin-template" ) func NewRouter() *gin.Engine { router := gin.New() render := eztemplate.New() render.TemplatesDir = "templates/" render.Ext = ".tmpl"...
package car import ( "testing" "github.com/stretchr/testify/assert" ) func TestCar(t *testing.T) { car := New(&Config{}) assert.NotNil(t, car) }
package roce import ( "errors" "fmt" "math" "runtime/debug" "strings" "sync" "time" "github.com/Huawei/eSDK_K8S_Plugin/src/connector" "github.com/Huawei/eSDK_K8S_Plugin/src/utils" "github.com/Huawei/eSDK_K8S_Plugin/src/utils/log" ) type connectorInfo struct { tgtPortals []string tgtLunGuids []string } ...
package posnode import ( "github.com/Fantom-foundation/go-lachesis/src/metrics" ) var ( countNodePeersTop = metrics.RegisterCounter("count_node_peers_top", nil) )
package stitchApi // List of types (eg s3, snowflake) GET /v4/destination-types // Get type details (eg Redshift) GET /v4/destination-types/{destination_type}
package message import ( "encoding/json" "fmt" "io/ioutil" "path/filepath" ) // Config contains the unmarshalled config.json type Config struct { Username string `json:"username"` URL string `json:"url"` Secrets struct { ClientID string `json:"client_id"` ClientSecret string `json:"client_secret"...
package main import ( "flag" "fmt" "os" "path/filepath" ) const ( majorVersion = 3 minorVersion = 0 patchVersion = 1 CONFIG_XML = "config.xml" CONFIG_JSON = "config.json" CONFIG_CACHE = "__cache__" ) var flagConfigFile string var flagOutputFile string var flagLegacy bool func init() { flag.StringVar(&...
package api import ( "GOLANG/entities" "GOLANG/models" "encoding/json" "math/rand" "net/http" ) func HashUrl(response http.ResponseWriter, request *http.Request) { urls, ok1 := request.URL.Query()["url"] userNames, ok2 := request.URL.Query()["username"] if !ok1 || !ok2 || len(urls) < 1 || len(userNames) < 1 {...
// 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. // +build windows package main import ( "os" "os/signal" "syscall" "github.com/OWASP/Amass/amass" ) // If the user interrupts the program, print the summary infor...
/* Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
package aoc2015 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_newPassword(t *testing.T) { assert := assert.New(t) testCases := []struct { input string want string }{ {"heqaabcc", "heqaabcc"}, {"heqa", "aaaaheqa"}, {"abcdefgH", "abcdefga"}...
package main import ( "bufio" "context" "fmt" "os" "strings" pb "github.com/AndreaEsposit/bachelors-thesis/echo_server/proto" "google.golang.org/grpc" ) func main() { conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) check(err) client := pb.NewEchoClient(conn) fmt.Println("Exit/exit' to exi...
package utils import ( "bytes" "fmt" "os/exec" ) func NginxReload(nginx string) error { cmd := exec.Command(nginx, "-s", "reload") var stderr bytes.Buffer cmd.Stderr = &stderr err := cmd.Run() if err != nil { return fmt.Errorf("NginxReload error: '%s' - '%s'", err, stderr.String()) } return nil }
/* Description 在嵌入式系统开发中,Modbus协议是工业控制系统中广泛应用的一种协议。本题用来简单模拟Modbus协议,只需根据条件生成符合该协议的数据帧,并解析所获取的数据。 假设设备使用的协议发送数据格式如下: <SlaveAddress, 1 Byte> <Function, 1 Byte> <Start Address, 2 Bytes> <NumberofBytes, 2 Bytes> <Checksum, 2 Bytes> 其中前四项将在输入条件中给出,最后一项为CRC校验和,需根据前四项的数据,按照CRC算法进行计算。注意数据的长度,多于1byte的高位在前,低位在后。该CRC校验算法的描述如下: ...
//Q8. Merge list and sort //Write a function that merges two sorted lists into a new sorted list, //e.g. merge([1,4,6], [2,3,5]) = [1,2,3,4,5,6]. //Code addapted from the following links //http://austingwalters.com/merge-sort-in-go-golang/ //https://gist.github.com/LordZamy/2adcb6d879fcef557d3d //https://stacko...
package main import ( "net/http" "log" "testwork1/src" ) func main() { http.HandleFunc("/", ppp.MainHandler) log.Print("Listen on 8080") log.Fatal(http.ListenAndServe(":8080", nil)) close(ppp.EmailChannel) }
// Copyright 2021 Google Inc. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This executable builds the Docker images based off the WASM executables in the // gcr.io/skia-public/skia-wasm-release image. It then issues a PubSub notification to have those ...
package model type Subscription struct { ID int CreditCardNumber string IsFraud bool IsIncomplete bool }
package base import ( "errors" "gengine/context" "reflect" ) type Arg struct { Constant *Constant Variable string FunctionCall *FunctionCall MethodCall *MethodCall MapVar *MapVar Expression *Expression } func (a *Arg) Evaluate(dc *context.DataContext, Vars map[string]reflect.Value) (reflec...
package bot import ( . "github.com/smartystreets/goconvey/convey" "testing" ) const ( serverName = "irc.server.com" ) func TestGetServerName(t *testing.T) { Convey("Given a config message", t, func() { config = &Config{} Convey("When there is no port specified", func() { config.Server = serverName So(g...
package geeRPC import ( "bufio" "encoding/gob" "io" ) type GobCodec struct { conn io.ReadWriteCloser buf *bufio.Writer dec *gob.Decoder enc *gob.Encoder } // var _ Codec = (*GobCodec)nil func NewGobCode(conn io.ReadWriteCloser) Codec { buf := bufio.NewWriter(conn) return &GobCodec{conn: conn, buf: buf, d...
package ismerror import "fmt" type IsmError struct { Code int Message string } func (err *IsmError) Error() string { return fmt.Sprintf("[%d] %s", err.Code, err.Message) }
package command import ( "fmt" "net/http" "testing" "github.com/mitchellh/cli" "github.com/stretchr/testify/assert" "github.com/romantomjak/b2/b2" "github.com/romantomjak/b2/testutil" ) func TestListCommand_CanListBuckets(t *testing.T) { server, mux := testutil.NewServer() defer server.Close() mux.Handle...
package upload import ( "bytes" "fmt" "log" "os/exec" "testing" "os" ) const ( TEST_FILE_DATA = "Test Data?" ) func TestGetMime(t *testing.T) { mime_t, err := Get_Mime("/local/testpic.png") if mime_t != "image/png" { if err == nil { t.Error("Error was not thrown for PNG") } t.Errorf("PNG mime type ...
package main import ( "context" "flag" "os" "os/signal" "time" "logstream/pkg/client" pb "logstream/pkg/proto" ) func main() { raddr := flag.String("raddr", ":8500", "remote address of upstream server") id := flag.String("id", "1", "unique ID of client") readFx := flag.Duration("freq", 1*time.Second, "freq...
package main /* func main() { sum := 1 for sum < 1000 { //초기화 구문과 사후 구문은 필수는 아님 sum += sum } fmt.Println(sum) } */ /*func main() { sum := 1 for sum < 1000 { //;을 생략할 수 있다는 점에서 C의 while == Go의 for sum += sum } fmt.Println(sum) }*/ /*func main() { for { } }*/ /* func sqrt(x float64) string { if x < 0 { ...
package utils import ( "time" "github.com/pquerna/otp" "github.com/pquerna/otp/totp" ) // 生成TOTP秘钥 func GenerateTOTPSecret(accountName string) (string, error) { key, err := totp.Generate(totp.GenerateOpts{ Issuer: "tpay", AccountName: accountName, Period: 30, Algorithm: otp.AlgorithmSHA512, ...
package hello import ( "fmt" "net/http" "github.com/gin-gonic/gin" "github.com/wkrzyzanowski/todox-go/server" ) const HELLO_BASE_URL = server.BASE_API_URL + "/hello" type HelloController struct { Endpoints []server.ApiEndpoint } func NewHelloController() *HelloController { return &HelloController{ Endpoint...
package store import ( "fmt" req "github.com/LapinDmitry/ExampleService/internal/store/sqlRequests" gen "github.com/LapinDmitry/ExampleService/third_party/grpcGenerated" "strconv" "time" ) const CommonLayout = "2006-1-2T15:04:05Z" // CreateUser - создать пользователя с набором предметов // func (s *Store) Creat...
/* Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. */ package main import ( "fmt" ) func count_evens(a []int) int { count := 0 for _, v := range a { if v % 2 == 0 { count++ } } return count } func main(){ var status int = 0 if count_even...
package main import ( "fmt" "os" ) func main() { channel := make(chan int) go func() { for i := 0; i < 10; i++ { channel <- i if i == 5 { close(channel) os.Exit(1) } } }() for i := range channel { fmt.Println(i) } }
package profile import ( "fmt" "sort" "sync" "time" ) type ProfileEntry struct { Calls int TotalTime time.Duration } type ProfileToken struct { Name string start time.Time } func (this *ProfileToken) Exit() { g_profiler.mutex.Lock() defer g_profiler.mutex.Unlock() var entry *ProfileEntry var ok bo...
package controllers import ( "net/http" "strconv" "github.com/martinyonathann/bookstore_items-api/domain/items" "github.com/martinyonathann/bookstore_items-api/logger" "github.com/martinyonathann/bookstore_items-api/services" "github.com/martinyonathann/bookstore_items-api/utils/errors" "go.uber.org/zap" "gi...
package main import "fmt" func main() { // var colors map[string]string // colors := make(map[string]string) // colors["white"] = "#ffffff" // delete(colors, "white") colors := map[string]string{ "red": "#ff0000", "green": "#4bf745", "white": "#ffffff", } //initalize map m := make(map[string]int) ...
package renderer import ( "bytes" "io/ioutil" "reflect" "strings" "text/template" "github.com/Altemista/render/files" "github.com/Altemista/render/renderer/configuration" "github.com/Masterminds/sprig" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) const ( // MissingKeyInvalidOption is the rendere...
package server import ( "log" "net/http" "github.com/sirupsen/logrus" ) //Server is a struct representing HTTP server type Server struct { mux *http.ServeMux logger *logrus.Logger } //NewServer returns a server with no routes func NewServer() *Server { return &Server{ mux: http.NewServeMux(), logger...
package oidc import ( "testing" "github.com/stretchr/testify/assert" ) func TestIsSigningAlgLess(t *testing.T) { assert.False(t, isSigningAlgLess(SigningAlgRSAUsingSHA256, SigningAlgRSAUsingSHA256)) assert.False(t, isSigningAlgLess(SigningAlgRSAUsingSHA256, SigningAlgHMACUsingSHA256)) assert.True(t, isSigningAl...
package main import ( "flag" "log" "net/http" "os" "github.com/evkuzin/consoleChatWs/server" "github.com/sirupsen/logrus" ) var addr = flag.String("addr", ":8080", "http service address") var logger = &logrus.Logger{ ReportCaller: true, Level: logrus.InfoLevel, Formatter: new(logrus.TextFormatter)...
package main import "fmt" func reverse_int(n int) int { new_int := 0 for n > 0 { remainder := n % 10 new_int *= 10 new_int += remainder n /= 10 } return new_int } func main() { result := 0 bigPal := 0 for i := 100; i < 1000; i++ { for j := 100; j < 1000; j++ { result = i * j if result == revers...
package tsmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document05000101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.050.001.01 Document"` Message *RoleAndBaselineRejectionV01 `xml:"RoleAndBaselnRjctn"` } func (d *Document05...
package env import ( "context" "net" "net/http" "os" "strings" "github.com/Azure/go-autorest/autorest" "github.com/sirupsen/logrus" "github.com/jim-minter/rp/pkg/env/dev" "github.com/jim-minter/rp/pkg/env/prod" ) type Interface interface { CosmosDB(ctx context.Context) (string, string, error) DNS(ctx con...
package gominin import ( "errors" "io" "sort" ) type SearchIndex interface { Add(in io.Reader) (Document, error) Search(query string) ([]DocID, error) } type searchIndex struct { store DocumentStore tokenizer Tokenizer termTable TermTable term2positions InvertedIndex } type termIDPositio...
/** * 公共配置类,用于加载数据库配置等 * Author: tesion * Date: 20th March 2019 * Note: * redis客户端配置受redis服务器配置影响 */ package config import ( "fmt" "github.com/go-ini/ini" ) const ( DEFAULT_DB_PORT = 3306 DEFAULT_DB_MAX_CONN = 10 DEFAULT_REDIS_PORT = 6379 DEFAULT_REDIS_TIMEOUT = 10 DEFAULT_REDIS_DB = 0 DEFAULT_REDIS_MA...
package main import "fmt" //有一堆桃子,猴子每天吃桃子总数的一半并多吃一个。吃了10天,到第11天只剩一个桃子。问,猴子吃之前,一共是多少个桃子。 func main() { fmt.Println(test(1)) } func test(day int) int { if day > 10 || day < 1 { return 0 } if day == 10 { return 1 } else { return (test(day+1) + 1) * 2 } }
package ltops import "io" // LoadTestOptions defines the possible options when starting a Mattermost load test. type LoadTestOptions struct { ForceBulkLoad bool // force bulk load even if previously loaded ResultsWriter io.Writer // writer to write the results to }
package acciones import ( "FileSystem-LWH/disco/ebr" "FileSystem-LWH/disco/mbr" "FileSystem-LWH/disco/particion" "FileSystem-LWH/util" "bytes" "encoding/binary" "fmt" "os" "strings" "unsafe" ) // Global var masterBootR mbr.MBR // CrearDisco crea el archivo binario func CrearDisco(size int64, path string, n...
package api import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" "github.com/makkes/gitlab-cli/config" ) var ErrNotLoggedIn = errors.New("you are not logged in") type Client interface { Get(path string) ([]byte, int, error) Post(path string, body i...
package main import ( "html/template" "path/filepath" "net/http" ) var templates map[string]*template.Template func InitTemplates() { if templates == nil { templates = make(map[string]*template.Template) } layouts, err := filepath.Glob("templates/layout/*.tmpl") if err != nil { Log("%v", err) ...
package main import "fmt" /** * author: will fan * created: 2019/6/30 14:22 * description: */ func main() { var x [5]int x[0] = 1 x[4] = 25 fmt.Println("X:", x) x[1] = 10 x[2] = 23 x[3] = 13 fmt.Println("X: ", x) y := [5]int{1,2,3,4,5} fmt.Println("Y: ", y) z := [...]int{6,7,8,9,10} fmt.Println("...
package my_package func Square(x float64) float64 { return x * x } func Add64(x float64) float64 { return x + 64 } type Result struct { number float64 } func HundredDividedBy(x float64) *Result { if x == 0. {return nil} return &Result {100. / x} }
package backend_dao import ( "2021/yunsongcailu/yunsong_server/dial" "2021/yunsongcailu/yunsong_server/web/web_model" ) type BackendLinkDao interface { // 获取所有链接 FindLinkAll() (linkList []web_model.LinksModel, err error) // 根据ID 修改链接 UpdateLinkById(link web_model.LinksModel) (err error) // 根据ID 修改链接图片 UpdateL...
package main import ( "testing" ) func TestLog(t *testing.T) { logger := &logger{Prefix: "hostname"} logger.warn("asd") // if debug != "debug log" { // t.Error("lalalal") // } }