text
stringlengths
11
4.05M
package main import ( "bytes" "fmt" "strings" ) const x = "hello" func withPlus() string { return x + x + x + x + x + x + x + x + x + x } func withSprintf() string { return fmt.Sprintf("%s%s%s%s%s%s%s%s%s%s", x, x, x, x, x, x, x, x, x, x) } func withBuffer() string { bb := &bytes.Buffer{} bb.WriteString(x) ...
package cmd import ( "github.com/spf13/cobra" bolt "go.etcd.io/bbolt" ) var db *bolt.DB // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "ceelei", Short: "Ceelei is a CLI helper inside the CLI to help you remember your commands.", Long: `Ceelei will...
package util import ( "log" "net/url" "os" "path/filepath" "strings" ) func GetCurrentDirectory() string { dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { log.Fatal(err) } return strings.Replace(dir, "\\", "/", -1) } func GetUrlDomain(urlStr string) string { urlInfo, err := url.Parse(u...
package data import ( "accountapi/lib" "encoding/json" "golang.org/x/text/currency" ) // Currency is a wrapper for currency Unit type that implements UnmarshalJSON. type Currency struct { currency currency.Unit } // NewCurrency from a currency.Unit. func NewCurrency(c currency.Unit) Currency { return Currency{...
package cmd import ( "context" "database/sql" "github.com/alewgbl/fdwctl/internal/config" "github.com/alewgbl/fdwctl/internal/database" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/model" "github.com/alewgbl/fdwctl/internal/util" "github.com/spf13/cobra" ) var ( desiredSta...
package baikal const ( manufactureName = "baikal" minerStopCMD = "sudo /opt/scripta/startup/miner-stop.sh" minerStartCMD = "sudo /opt/scripta/startup/miner-start.sh" minerConfPath = "/opt/scripta/etc/miner.conf" minerOptionsPath = "/opt/scripta/etc/miner.options.json" minerPoolsPath = "/opt/scripta/et...
package usecase import ( "context" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/superj80820/2020-dcard-homework/domain" ) // RateLimitUsecase ... type rateLimitUsecase struct { RateLimitRepo domain.RateLimitRepository } // NewRateLimitUsecase ... func NewRateLimitUsecase(rateLimitRepo domai...
package config import ( "encoding/json" "errors" "strconv" "strings" "time" ) // time.Duration forces you to specify in millis, and does not support days // see https://stackoverflow.com/questions/48050945/how-to-unmarshal-json-into-durations type TTL time.Duration func (l TTL) MarshalJSON() ([]byte, error) { ...
package cain import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00800101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:cain.008.001.01 Document"` Message *ReconciliationResponse `xml:"RcncltnRspn"` } func (d *Document00800101) AddMessag...
package main import ( "encoding/binary" "io" "log" "os" "os/signal" "strings" "syscall" "time" "github.com/bwmarrin/discordgo" "github.com/lainbot/cmd" "github.com/lainbot/framework" ) var ( conf *framework.Config CmdHandler *framework.CommandHandler Sessions *framework.SessionManager youtube ...
package prof /* |* Handlers: \***********************************/ import ( "encoding/json" "log" "net/http" "github.com/gorilla/mux" "github.com/sirupsen/logrus" "gitlab.com/NagByte/Palette/service/auth" "gitlab.com/NagByte/Palette/service/common" ) func (ps *profService) getProfileHandler(w http.ResponseW...
package utils import ( "github.com/ipipdotnet/ipdb-go" "log" ) var db *ipdb.BaseStation func initIpIp() { var err error db, err = ipdb.NewBaseStation("ipipfree.ipdb") if err != nil { log.Fatal(err) } } func GetAddress(ip string) string { ips, err := db.FindMap(ip, "CN") if err != nil { return "unknown" ...
package inttest import ( "context" "fmt" "os" "path/filepath" "reflect" "testing" "go.mongodb.org/mongo-driver/mongo/options" "tagallery.com/api/config" "tagallery.com/api/model" "tagallery.com/api/mongodb" "tagallery.com/api/testutil" "tagallery.com/api/util" ) var processedImageFixtures = []model.Image...
package cryptutil import ( "crypto/x509" "strings" ) type certUsage byte const ( certUsageServerAuth = certUsage(1 << iota) certUsageClientAuth ) // A CertificatesIndex indexes certificates to determine if there is overlap between them. type CertificatesIndex struct { index map[string]map[string]certUsage } /...
package delivery import ( "context" "fmt" "net/http" ) // KlinesService list klines type KlinesService struct { c *Client symbol string interval string limit *int startTime *int64 endTime *int64 } // Symbol set symbol func (s *KlinesService) Symbol(symbol string) *KlinesService { s.symbol...
package main import ( "context" "fmt" "io" "os" "code.cloudfoundry.org/lager" "github.com/chendrix/pm/lib/gh" "github.com/chendrix/pm/lib/tablewriter" "github.com/google/go-github/github" "github.com/jessevdk/go-flags" "github.com/vito/twentythousandtonnesofcrudeoil" "golang.org/x/oauth2" ) type Passenger...
package main import ( "fmt" "sync" "time" ) func main() { var mutex sync.Mutex fmt.Println("main 即将锁定mutex") mutex.Lock() fmt.Println("main 已经锁定mutex") for i:=1;i<=3;i++ { go func(i int) { fmt.Println("子goroutime",i,"即将锁定mutex..") mutex.Lock() fmt.Println("子goroutime",i,"已经锁定mutex..") }(i) } ti...
package main func main() { for i := 10; i <= 100; i++ { println(i % 4) } }
package main import ( "flag" "fmt" "github.com/mschewe/pin/lib" ) var length, count int func init() { flag.IntVar(&length, "n", 4, "length of the pin") flag.IntVar(&count, "c", 1, "number of generated pins") flag.Parse() } func main() { for i := 0; i < count; i++ { fmt.Println(pin.Generate(length)) } }
package controllers import ( "accountBook/models/beans" "accountBook/models/log" "context" "fmt" "net" "os" "time" "github.com/kinwyb/go" "github.com/shirou/gopsutil/process" "github.com/astaxie/beego" "github.com/rcrowley/go-metrics/exp" "github.com/rcrowley/go-metrics" "github.com/vrischmann/go-metri...
package ldap import ( "github.com/go-ldap/ldap" "log" ) func (s *LDAPStore) PasswordChange(uid, oldPasswd, newPasswd string) (err error) { for _, ls := range s.sources { err = ls.PasswordChange(uid, oldPasswd, newPasswd) if err != nil { log.Printf("PasswordChange at %s ERR: %s", ls.Addr, err) } } return...
package main func containers() { //Group Box createWidget("Group Box", ` Item { GroupBox { anchors.centerIn: parent title: "Group Box" ColumnLayout { Button { text: "Push Button: 0" } Button { text: "Push Button: 1" } Button { text: "Push Button...
package app import ( "context" "time" "github.com/bobrovka/calendar/internal/models" "go.uber.org/zap" ) // App интерфейс приложения type App interface { ListDayEvents(ctx context.Context, user string, date time.Time) ([]*models.Event, error) ListWeekEvents(ctx context.Context, user string, date time.Time) ([]...
package prometheus import ( stdprometheus "github.com/prometheus/client_golang/prometheus" ) func RegisterMetrics(cs ...stdprometheus.Collector) { for _, c := range cs { if err := stdprometheus.Register(c); err != nil { CheckRegisterError(err) } } } func CheckRegisterError(err error) { if register, ok := ...
package Cmd /** * 账户模块 */ const ( Account_Register uint32 = 1001 // 注册 Account_PasswordLogin uint32 = 1002 // 密码登录 Account_TokenLogin uint32 = 1003 // Token登录 ) /** * 服务器模块 */ const ( Server_List uint32 = 2001 // 列表 Server_Select uint32 = 2002 // 选服 )
package goevent_test import ( "sync" "testing" "github.com/indie21/goevent" ) func TestEventNew(t *testing.T) { p := goevent.New() t.Log("Event: %+v", p) } func TestOnTrigger(t *testing.T) { p := goevent.New() i := 1 err := p.On(func(j int) { i += j }) if err != nil { t.Fatal(err) } err = p.Trigge...
/* Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. Example 1: Input: n = 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: n = 5 Output: 1 Explanation: 5! = 120, one trailing zero. Example 3: Input: n = 0 Output: 0 Constrai...
package array func InArray(need string, itemList []string) bool { result := false for _, item := range itemList { if item == need { result = true } } return result } func ArrayKeyExists() { }
package kubectl import ( "net/http" "time" "github.com/devspace-cloud/devspace/pkg/devspace/kubectl/transport" "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/client-go/transport/spdy" ) // UpgraderWrapper wraps the upgrader and adds a connections array type UpgraderWrapper interface { NewConnection(resp *ht...
package main import ( "fmt" "log" "time" "github.com/BoutiqaatREPO/nitrous/sequencer" ) func main() { // // Initializing Sequencer. // seq, err := sequencer.GetRollingSequencer(sequencer.Key{ Name: "testrol", Bucket: "test", }, sequencer.Limits{ Start: 1, End: 10, }, sequencer.REDIS_ADAPTER, ...
package main import "fmt" func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { l1 := len(nums1) l2 := len(nums2) if (l1+l2)%2 == 1 { return float64(findK(nums1, nums2, 1+(l1+l2)/2)) } else { return float64(findK(nums1, nums2, (l1+l2)/2) + findK(nums1, nums2, 1+(l1+l2)/2))/2....
// Copyright Jetstack Ltd. See LICENSE for details. package cmd import ( "fmt" "path/filepath" "github.com/spf13/cobra" "github.com/jetstack/vault-helper/pkg/cert" "github.com/jetstack/vault-helper/pkg/kubeconfig" ) // initCmd represents the init command var kubeconfCmd = &cobra.Command{ Use: "kubeconfig [c...
package diffiehellman // Step 1: PrivateKey(p *big.Int) *big.Int // Step 2: PublicKey(private, p *big.Int, g int64) *big.Int // Step 2.1: NewPair(p *big.Int, g int64) (private, public *big.Int) // Step 3: SecretKey(private1, public2, p *big.Int) *big.Int import ( "crypto/rand" "math/big" ) // PrivateKey retu...
/** * Copyright 2019 Comcast Cable Communications Management, LLC * * 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 requir...
package webdav import ( "fmt" "github.com/Sirupsen/logrus" "github.com/julienschmidt/httprouter" "net/http" ) func (api *API) unlock(w http.ResponseWriter, r *http.Request, p httprouter.Params) { authRes, err := api.basicAuth(r) if err != nil { logrus.Error(err) w.Header().Set("WWW-Authenticate", "Basic Re...
package main import "fmt" var x int type person struct { Fname string Lname string } type secreteAgent struct { person lisenceToKill bool } type human interface { speak() } func saySomething(h human) { h.speak() } func (p person) speak() { fmt.Println(p.Fname, p.Lname, `is not the hero`) } func (sa secre...
package cmd import ( "github.com/spf13/cobra" "github.com/sylus/openparl/api" "github.com/sylus/openparl/models" "github.com/sylus/openparl/routes" "github.com/urfave/negroni" ) // serveCmd represents the serve command var serveCmd = &cobra.Command{ Use: "serve", Short: "A brief description of your command"...
package config import ( "bytes" "testing" ) func TestLoadConfig(t *testing.T) { test_data := `{ "HttpPort": ":8080", "AWS_AccessKey": "accesscode", "AWS_SecretKey": "password", "DB": "localhost:5000" }` buffer := bytes.NewBufferString(test_data) config := LoadConfig(buffer) if config.HttpPort != ":80...
package main import ( "log" "os" "time" "github.com/uvalib/virgo4-sqs-sdk/awssqs" ) // // main entry point // func main() { log.Printf("===> %s service staring up (version: %s) <===", os.Args[0], Version()) // Get config params and use them to init service context. Any issues are fatal cfg := LoadConfigurat...
package command import "strconv" // TODO: read discord dev docs and finish validation // Check if the JSON payload for creating a command is valid func (cmd Command) Validate() []error { errors := make([]error, 0) if cmd.Name == "" { errors = append(errors, MissingCommandField{FieldName: "name", Path: cmd.Name +...
package config import ( "gin-jwt/structs" "io/ioutil" "github.com/buger/jsonparser" "github.com/jinzhu/gorm" ) // DBInit create connection to database func DBInit() *gorm.DB { json, err := ioutil.ReadFile("./config/config.json") dbengine, err := jsonparser.GetString(json, "databases", "[0]", "engine") dbconns...
package aoc2020 import ( "fmt" "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_conwayCube(t *testing.T) { // aliases for later T, F := true, false assert := assert.New(t) cube, err := newConwayCube(day17sampleInput) assert.NoError(err) assert.Equal(conwayC...
package dao import ( "CloudRestaurant/model" "CloudRestaurant/tool" ) type FoodCategoryDao struct { *tool.Orm } //实例化Dao对象 func NewFoodCategoryDao()*FoodCategoryDao{ return &FoodCategoryDao{tool.DbEngine} } //从数据库中查询所有的食品种类,并返回 func (fcd *FoodCategoryDao)QueryCategories()([]model.FoodCategory,error){ var cate...
package classic // ListNode definition for linked list node type ListNode struct { // singly-linked list Val int `json:"val"` Next *ListNode `json:"next"` // extra for doubly-linked list Prev *ListNode `json:"-"` // extra for multilevel doubly-linked list Child *ListNode `json:"-"` // extra for copy ...
package cache import ( "fmt" ) func PrettyUuidAndHash(d []byte) string { return fmt.Sprintf("%x/%x", d[:16], d[17:]) }
// Package ast contains the definitions of the abstract-syntax tree // that our parse produces, and our interpreter executes. package ast import ( "bytes" "github.com/kasworld/nonkey/interpreter/asti" "github.com/kasworld/nonkey/interpreter/token" ) // Program represents a complete program. type Program struct { ...
package cmd import ( "encoding/json" "fmt" "strings" "code.cloudfoundry.org/cli/plugin" ) type Stacks struct { Resources []StackResource `json:"resources"` Pagination StacksPagination `json:"pagination"` } type StacksPagination struct { TotalPages int `json:"total_pages"` } type StackResource struct { GU...
package example import ( "time" "github.com/bearchit/goclock" ) type User struct { Name string CreatedAt time.Time } type App struct { Clock goclock.Clock } func (app App) NewUser(name string) User { return User{ Name: name, CreatedAt: app.Clock.Now(), } }
package russian func rublesByCase(nnc numeralNumberCase) string { switch nnc { case singularNominative: return "рубль" case singularGenitive: return "рубля" case pluralGenitive: return "рублей" default: return "" } } // Rubles returns russian for "ruble" corresponding to 'amount'. func Rubles(amount int...
package serverconfigs import ( "testing" ) func TestGzipConfig_MatchContentType(t *testing.T) { }
package main import ( "fmt" ) func main() { var f, c = 32.0, 212.0 fmt.Printf("%f\n", fTOc(f)) fmt.Printf("%f\n", fTOc(c)) x := 1 p := &x fmt.Printf("%d point is %p,vlaue is %v\n,p is %v", x, p, *p, &p) } func fTOc(t float64) float64 { return (t - 32) * 5 / 9 }
package leetcode /*Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.  Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows a, b are from arr a < b b - a equals to the minimum absolute difference of any tw...
package handlers import ( "fmt" "net/http" ) func CommentHandler(write http.ResponseWriter, request *http.Request) { fmt.Fprintln(write, "Welcome! Joe") }
package paxos import ( "time" ) type Acceptor { starttime *time.Time messages []*Message number uint } func NewAcceptor()*Acceptor { acceptor := new(Acceptor) acceptor = time.Now() acceptor.messages = []*Message{} return acceptor } func (acceptor *Acceptor) Start() { go acceptor.process() } func (accept...
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package filter contains a stateful packet filter. package filter import ( "sync" "time" "github.com/golang/groupcache/lru" "golang.org/x/ti...
package interp import ( "fmt" protodesc "github.com/jhump/protoreflect/desc" "go.starlark.net/starlark" "go.starlark.net/syntax" ) // ProtoEnumType is a starlark.Value that repsents a protobuf enum type ProtoEnumType struct { name string values map[string]int32 } var _ protoType = (*ProtoEnumType)(nil) var ...
/* Go Language Raspberry Pi Interface (c) Copyright David Thorpe 2016-2017 All Rights Reserved Documentation http://djthorpe.github.io/gopi/ For Licensing and Usage information, please see LICENSE.md */ package tsl2561 import ( "fmt" "time" gopi "github.com/djthorpe/gopi" sensors "github.com/djthorpe/se...
package goo_mq import ( "fmt" "github.com/Shopify/sarama" "github.com/liqiongtao/goo" ) type KafkaConsumerGroup struct { *Kafka GroupId string Handler HandlerFunc } func (*KafkaConsumerGroup) config() *sarama.Config { config := sarama.NewConfig() config.Consumer.Offsets.Initial = sarama.OffsetOldest config....
package rpi import ( "fmt" "github.com/stianeikeland/go-rpio" ) func Cleanup() { err := rpio.Close() if err != nil { panic(err) } } func Init() error { err := rpio.Open() if err != nil { return fmt.Errorf("failed to init rpi: %s", err) } return nil }
package services import ( "encoding/json" "errors" "cuproad/cuproad-api-go/couchdb" "github.com/google/uuid" ) type ChampionServiceImpl struct { DBInstance *couchdb.CouchDatabase } //Add create new champion func (cs *ChampionServiceImpl) Add(champion *Champion) (Champion, error) { champion.ID = uuid.New().St...
package streamdal import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Streamdal", func() { Context("ListCollections", func() { It("returns an error when empty", func() { b := StreamdalWithMockResponse(200, `[]`) output, err := b.listCollections() Expect(err).To(Equal(errN...
package main import ( "strings" "fmt" ) func main() { var hasil = strings.Contains("anu madam", "madam"); // mengecek apakah tulisan madam ada didalam tulisan anu madam. hasil return bool var isPrefix1 = strings.HasPrefix("john wick", "jo"); // mengecek apakah tulisan jo ada diawal tulisan john wich atau fung...
package g2util import ( "bytes" "errors" "fmt" "io" "log" "os" "path/filepath" "regexp" "strings" "sync" "time" ) //每秒写入到文件一次,阻塞当前数据写入 //当buffer超过指定值,写入到文件 //自动对大文件进行打包 //自动删除n天前的文件 // 常量,大小定义 const ( _ int = 1 << (10 * iota) //ignore KB _ MB ) // IWriter ... type IWriter interface { AfterShutdown()...
package models import ( "fmt" "io" "regexp" "strings" "time" "github.com/iancoleman/strcase" "github.com/pkg/errors" "gopkg.in/yaml.v3" ) var ( capitalsRegex = regexp.MustCompile(`[A-Z][^A-Z]*`) ) // Component is a piece of a service that provides processors that accomplish a task type Component struct { ...
package partial import ( "text/template" ) var FuncMap = template.FuncMap { "file": File, "partial": Partial, }
package main import ( "fmt" "log" "os" "strconv" "./assembly" "golang.org/x/sys/windows/registry" ) func init(){ Version := versionFunc() if Version == "10.0" { err := RefreshPE(`c:\windows\system32\kernel32.dll`) if err != nil { log.Println("RefreshPE failed:", err) } err = R...
//Akshy Palanisamy //Lexical Analyzer for Hunter-Power-Gramar package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" "unicode" ) func main() { //Checking for test file input if len(os.Args) <= 1 { fmt.Println("Please input a test file.") return } //retriving test file name readFileName := ...
package connect import "os" func Initialization(serviceName string) { _ = ConnectLog(serviceName) _ = ConnectStdLog(serviceName) if isProduction() { //InitJaeger(serviceName) MysqlInit(serviceName) } } func isProduction() bool { if os.Getenv("POD_NAMESPACE") == "production" { return true } else { retur...
package dictionary // import( // "github.com/Evedel/fortify/src/say" // ) func ruleAssignment(ttail []Token) (resCode int, stopInd int, resNode TokenNode, errmsg string) { thisName := "ruleAssignment: " resCode = UndefinedError stopInd = 0 index := 1 chStopIndx := 0 lhs := []TokenNode{} rhs := TokenNode{} l...
package config import ( "testing" ) func Test_load(t *testing.T) { LoadAppConf("./rpc.yaml") t.Logf("app config:%+v", App) for k1, c := range App.Plugins { t.Logf("k1:%+v, %+v", k1, c) } type logger struct { Level string `yaml:"level"` Path string `yaml:"path"` RollType string `yaml:"roll_type"...
package ss_manager import ( "net/url" ) type SSManager struct { Port int Url string } func (s *SSManager) Init(Url string) *SSManager { addr, cipher, password, err := parseURL(Url) if err != nil { } } type AllManager struct { } func parseURL(s string) (addr, cipher, password string, err error) { u, err := ...
package Metodos import ( "bufio" "bytes" "encoding/binary" "fmt" "log" "math/rand" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "time" "unsafe" "../Structs" ) func ReadFile(path string, mbr Structs.MBR) { file, err := os.Open(path) defer file.Close() if err != nil { log.Fatal(err) ...
package middleware import ( "fmt" "log" "github.com/gin-gonic/gin" "github.com/wkrzyzanowski/todox-go/server" ) func NewLoggerMiddleware() server.ApiMiddleware { return server.ApiMiddleware{ Name: "Logging Middleware", Function: logRequest(), } } func logRequest() gin.HandlerFunc { return func(ctx *g...
package request import ( "math/rand" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } // RandInt returns a pseudo-random number in [0,max) func RandInt(max int) int { return rand.Intn(max) }
package fluent import ( "testing" "time" "github.com/stretchr/testify/require" ) func Test_Where(t *testing.T) { require := require.New(t) f := &Fluent{} timestamp := time.Now() tests := []struct { where [][]interface{} expectedArgs []interface{} expectedArgCounter int expectedSt...
package file import ( "io/ioutil" "log" "os" "strings" ) // Loads a file from path. // Returns the byte array corresponding to file's contents. func Load(path string) []byte { file, err := ioutil.ReadFile(path) if err != nil { log.Fatalf("error: %v", err) os.Exit(1) } return file } // Gets the names of...
package instrument // Allow to wrap multiple collectors as one collector import ( "time" confluent "github.com/confluentinc/confluent-kafka-go/kafka" ) // MultiCollector allows you to compose a list of collector type MultiCollector struct { collectors []Collector } // NewMultiCollector is a constructor for multi...
package sqlc import ( "database/sql" "fmt" log "github.com/cihub/seelog" ) func FilterBindata(filter string, r func(string) ([]string, error)) []string { assetNames, _ := r(filter) for i, name := range assetNames { assetNames[i] = fmt.Sprintf("%s/%s", filter, name) } return assetNames } func LoadBindata(a...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/9/11 7:07 下午 # @File : lt_88_合并两个有序数组.go # @Description : # @Attention : */ package offer // 题目关键: 数组排序递增的 // 解题关键: 双指针 func merge1(nums1 []int, m int, nums2 []int, n int) { for mp, np, cur := m-1, n-1, m+n-1; mp >= 0 || np >= 0; cur-- { var v int if mp ...
package main import ( "github.com/chrilnth/apikeymanager/config" "github.com/chrilnth/apikeymanager/routes" "github.com/gofiber/cors" "github.com/gofiber/fiber" ) const port = 8000 func setupRoutes(app *fiber.App) { app.Get("", func(c *fiber.Ctx) { c.Status(fiber.StatusOK).JSON(fiber.Map{ "success": true,...
package config import "github.com/SOMAS2020/SOMAS2020/internal/common/shared" // SelectivelyVisibleFloat64 represents a wrapped float64 whose value is valid only if the Valid flag is set to true type SelectivelyVisibleFloat64 struct { Value float64 Valid bool } func getSelectivelyVisibleFloat64(value float64, vali...
package job import ( "context" "sync" "sync/atomic" "time" "github.com/google/uuid" "github.com/odpf/optimus/core/tree" "github.com/odpf/optimus/models" "github.com/odpf/optimus/store" "github.com/odpf/optimus/utils" "github.com/odpf/salt/log" "github.com/pkg/errors" "github.com/robfig/cron/v3" ) var ( ...
package model import "errors" type IUserModel interface { GetUserByID(id string, result *UserModel) error } type UserModel struct { ID string `json:"id"` Name string `json:"name"` } func NewUser() IUserModel { return &UserModel{} } func (u UserModel) GetUserByID(id string, result *UserModel) error { // Shou...
package controller import ( "github.com/gin-gonic/gin" "net/http" "ginSession/model" "ginSession/dao" ) func AccessIndex(c *gin.Context) { c.HTML(http.StatusOK,"index.html",nil) } func Register(c *gin.Context) { var user model.UserRegister c.BindJSON(&user) if !model.CheckIsRegister(user.UserName){ c.JSON(...
package module const ( Placeholder = "// this line is used by starport scaffolding # 1" Placeholder2 = "// this line is used by starport scaffolding # 2" Placeholder2_1 = "// this line is used by starport scaffolding # 2.1" Placeholder3 = "// this line is used by starport scaffolding # 3" Placeholder4 = ...
package main import ( "errors" "fmt" "math" "strings" "time" ) // ▸ go run main.go // [2019-01-27T15:59:19Z] [run start] // [2019-01-27T15:59:19Z] [getB start] // [2019-01-27T15:59:19Z] [getA start] // [2019-01-27T15:59:20Z] .[getB end: 3 <nil>] // [2019-01-27T15:59:22Z] ...[getA end: A <nil>] // [2019-01-27T15:...
package coda import ( "fmt" "log" ) type Row struct { Id string `json:"id"` Type string `json:"type"` Href string `json:"href"` Name string `json:"name"` Index int `json:"index"` BrowserLink ...
package leetcode import ( "fmt" "testing" ) func TestReverseKGroup(t *testing.T) { l := &ListNode{} h := l for i := 1; i < 8; i++ { l.Val, l.Next = i, &ListNode{Val: i + 1} l = l.Next } l = reverseKGroup(h, 3) fmt.Println(l) } func TestReverseKGroup2(t *testing.T) { l := &ListNode{} h := l for i := 1...
package model type DeliveryRequest struct { ID string Quantity int Theatre Theatre }
package main import ( "bytes" "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "strconv" "testing" "github.com/gin-gonic/gin" "github.com/guilhermeonrails/api-go-gin/controllers" "github.com/guilhermeonrails/api-go-gin/database" "github.com/guilhermeonrails/api-go-gin/models" "github.com/stretch...
package main import ( "os" "os/signal" log "github.com/Sirupsen/logrus" "github.com/nats-io/nats" ) const msgSubject = "natssample.reply" func main() { natsURL := nats.DefaultURL if len(os.Getenv("NATS_HOST")) > 0 { natsURL = "nats://" + os.Getenv("NATS_HOST") } nc, err := nats.Connect(natsURL) if err !...
/* 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, softw...
//Var reference in an sibling scope package main func main () { var x = 5; var y = x; x = y; } func pain () { var y = x; return; }
package main import ( "fmt" "context" hw "learn_go/learnrpcx/genprobuf/hw" server "github.com/smallnest/rpcx/server" ) // GreetImpl type GreetImpl struct{} func main(){ s := server.NewServer() s.RegisterName("Greet",new(GreetImpl),"") err := s.Serve("tcp",":8972") if err != nil { panic(err) } } func (s ...
/* * Minio Client (C) 2014, 2015 Minio, 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 ...
package main import ( "crypto/tls" "flag" "fmt" "net/http" "net/url" "os" "strconv" "strings" "time" ) func main() { // parse flags // host := flag.String("host", "", "Host address to grab the certs from. Hostname or full `URL`") outfile := flag.Bool("w", false, "Write certs to a file instead of stdout.")...
/* Copyright 2020 Frederic Branczyk All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed ...
package plugin import ( "fmt" "github.com/backforty/go-harvest/harvest" "log" "strings" ) func Harvest() { s, err := getEnvValue("HARVEST") if err != nil { log.Fatalf("Error finding HARVEST env: %v", err) } credentials := strings.Split(s, ":") apiClient := harvest.NewAPIClientWithBasicAuth(credentials[0]...
package conclusion import ( "strconv" "strings" ) // TreeNode is definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func (n *TreeNode) String() string { return "[" + strings.TrimRight(strings.Join(bfs(n), ","), ",null") + "]" } func generateTrees(n int) []*Tr...
// 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...