text stringlengths 11 4.05M |
|---|
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Command analyze performs sentiment, entity, and syntax analysis
// on a string of text via the Cloud Natural Language API.
package main
import (
"encoding/j... |
package terraform
import (
"os"
"strings"
)
type Provider struct {
Name string
Variables map[string]interface{}
}
func NewProvider(name string) *Provider {
provider := new(Provider)
provider.Name = name
provider.Variables = make(map[string]interface{})
return provider
}
func (provider *Provider) AddVariabl... |
package autoscaler
type Subnet struct {
SubnetID string `yaml:"SubnetID" validate:"required"`
AvailabilityZone string `yaml:"AvailabilityZone" validate:"required"`
}
|
package cmd
import (
"fmt"
"log"
"path/filepath"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zerostick/zerostick/daemon/watchers"
"github.com/zerostick/zerostick/daemon/web"
)
// serveCmd represents the serve command
var (
cfgListen = "0.0.0.0:8080"
serveCmd = &cobra.Command{
Use: "se... |
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func NeuralNetwork() *NN {
rand.Seed(time.Now().UnixNano())
data := make([][]float64, 3)
for i := range data {
data[i] = []float64{2*rand.NormFloat64() - 1}
}
return &NN{
SynapticWeights: data,
}
}
type NN struct {
SynapticWeights [][]float64
}
... |
package main
import (
"bufio"
"bytes"
"crypto/rand"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
houndify "github.com/soundhound/houndify-sdk-go/houndify"
)
const (
// This is not the clientId. This is the app user, so many will likely exist per clientId.
// This value can be any string.
// See https:/... |
package bgControllers
import (
"github.com/astaxie/beego"
"GiantTech/models"
"fmt"
"GiantTech/controllers/tools"
"strconv"
"strings"
)
type BgProjectUploadFileController struct {
beego.Controller
}
func (this *BgProjectUploadFileController) Prepare() {
s := this.StartSession()
username = s.Get("login")
bee... |
/*
* @lc app=leetcode.cn id=1797 lang=golang
*
* [1797] 设计一个验证系统
*/
// @lc code=start
// package leetcode
type AuthenticationManager struct {
timeToLive int
tokenMap map[string]int
}
func Constructor(timeToLive int) AuthenticationManager {
return AuthenticationManager{
timeToLive: timeToLive,
tokenMap: ma... |
package main
import (
"fmt"
"strings"
"jblee.net/adventofcode2018/utils"
)
type dependency struct {
first, second int
}
func lines2Dep(lines []string) []dependency {
deps := make([]dependency, len(lines))
for idx, line := range lines {
deps[idx].first = int(line[5])
deps[idx].second = int(line[36])
}
r... |
package main
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"periph.io/x/periph/conn/gpio"
"periph.io/x/periph/conn/gpio/gpioreg"
"periph.io/x/periph/host"
"strings"
"time"
)
var edgeTimeout time.Duration
var out_write gpio.PinIO
var out_read gpio.PinIO
var out_reserved2 gpio.PinIO
var out_reserved1 gpio.P... |
package cmd
import (
"github.com/spf13/cobra"
"github.com/wish/ctl/cmd/util/parsing"
"github.com/wish/ctl/pkg/client"
// "io"
"bufio"
)
func logsCmd(c *client.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "logs pod [flags]",
Aliases: []string{"log"},
Short: "Get log of a container in a pod",... |
package shared
import (
"encoding/json"
"encoding/xml"
"net/http"
"reflect"
"runtime"
utils "github.com/agungdwiprasetyo/go-utils"
)
// HTTPResponse abstract interface
type HTTPResponse interface {
JSON(w http.ResponseWriter)
XML(w http.ResponseWriter)
}
type (
// httpResponse model
httpResponse struct {
... |
// 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 reset
import (
"github.com/devspace-cloud/devspace/pkg/util/factory"
"github.com/spf13/cobra"
)
type keyCmd struct {
Provider string
}
func newKeyCmd(f factory.Factory) *cobra.Command {
cmd := &keyCmd{}
keyCmd := &cobra.Command{
Use: "key",
Short: "Resets a cluster key",
Long: `
###############... |
package main
import (
"log"
"net/http"
l "github.com/eriklindqvist/recepies_api/app/lib"
)
func main() {
log.Printf("Server started")
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(l.Getenv("FILEBASE", "files")))))
if err := http.ListenAndServe(":" + l.Getenv("PORT", "3003"), nil); err != nil... |
// Copyright 2018, OpenCensus 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 agree... |
package router
import (
"log"
"net/http"
"garduino/controllers"
"github.com/julienschmidt/httprouter"
)
// Listen and route connections.
func Listen() {
router := httprouter.New()
router.POST("/", controllers.Injest)
log.Fatal(http.ListenAndServe(":8080", router))
}
|
package controller
import (
"GoCRUDs/internal/handler"
"GoCRUDs/pkg/constants"
"GoCRUDs/pkg/request"
"GoCRUDs/pkg/response"
"GoCRUDs/pkg/utils"
"encoding/json"
"io/ioutil"
"net/http"
)
var userHandler *handler.UserHandler
func init() {
userHandler = handler.GetUserHandler()
}
func CreateUser(w http.Respons... |
package operation
import (
"fmt"
"math"
)
const swapV2ConfTarget = 250 // Approx 2 days
// TODO: we should make FeeWindow enforce a non empty Map of TargetedFees via constructor
type FeeWindow struct {
TargetedFees map[uint]float64
}
// Get the appropriate fee rate for a given swap (depends on confirmations need... |
package main
import (
"fmt"
"math"
)
func solve() int {
var cnt int
n := 1
var t int
for t < 10 {
t = int(math.Ceil(math.Pow(10, float64(n-1)/float64(n))))
cnt += 10 - t
n++
}
return cnt
}
func main() {
fmt.Println(solve())
}
// How many n-digit positive integers exist which are also an nth power?
//... |
package main
import (
"context"
"fmt"
"log"
"sync"
"sync/atomic"
"time"
pb "github.com/IgorBaskakov/service/cache"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
const (
address = "localhost:50051"
maxConnection = 500
maxLen = 100
)
func sendGRPCRequest(wg *sync.WaitGroup, o... |
package namespace
import (
"context"
"os"
)
const (
MREPL int = iota
MBEFORE
MAFTER
)
type Namespace interface {
Bind(new, old string, flags int)
Mount(new, old string, flags int)
Cmd(ctx context.Context, cmd string, args ...string) Cmd
Mkdir(name string) error
Open(name string) (*os.File, error)
OpenFile... |
// Package api provides an example on how to use go-fuzz.
package api
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
// Need a named type for our user.
type user struct {
Type string
Name string
Age int
}
// Routes initialize the routes.
func Routes() {
http.HandleFunc("/process", Pr... |
package datastruct
import "fmt"
func ExampleStack() {
// test for type int
intStack := NewStack(10)
intStack.Push(10)
intStack.Push(1)
intStack.Push(-5)
fmt.Println(intStack.Top())
intStack.Pop()
intStack.Push(5)
for !intStack.IsEmpty() {
fmt.Println(intStack.Top())
intStack.Pop()
}
// test for typ... |
package main
import (
"fmt"
"log"
"net/http"
"github.com/PuerkitoBio/goquery"
)
//GetData Function to get the html
func GetData(url string) {
res, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("status code error: %d %s", res.StatusCod... |
package dontknowtrade
import (
"github.com/shopspring/decimal"
"github.com/quickfixgo/quickfix"
"github.com/quickfixgo/quickfix/enum"
"github.com/quickfixgo/quickfix/field"
"github.com/quickfixgo/quickfix/fix40"
"github.com/quickfixgo/quickfix/tag"
)
//DontKnowTrade is the fix40 DontKnowTrade type, MsgType = Q... |
package externalservices
import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"poliskarta/api/structs"
"strings"
"sync"
)
func CallMapQuest(policeEvent *structs.PoliceEvent, credentials structs.Credentials, wg *sync.WaitGroup) {
mapURL := "http://open.mapquestapi.com/geocoding/v1/address?... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type Const struct {
Xpr ast.Node
Consttype Oid
Consttypmod int32
Constcollid Oid
Constlen int
Constvalue Datum
Constisnull bool
Constbyval bool
Location int
}
func (n *Const) Pos() int {
return n.Location
}
|
package install
const (
StrategyErrReasonComponentMissing = "ComponentMissing"
StrategyErrReasonAnnotationsMissing = "AnnotationsMissing"
StrategyErrReasonWaiting = "Waiting"
StrategyErrReasonInvalidStrategy = "InvalidStrategy"
StrategyErrReasonTimeout = "Timeout"
StrategyErrReasonUnkn... |
package env
import "os"
// GetWithDefault simplifies accessing env variables by allowing you get a default if the variable is not set
func GetWithDefault(key string, substitute string) string {
s := os.Getenv(key)
if s == "" {
s = substitute
}
return s
}
|
package main
import (
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/dlockamy/goRouter/config"
"github.com/dlockamy/goRouter/todo"
)
func Routes(configuration *config.Config) *chi.Mux {
router := chi.NewRouter()
router.Use(... |
package middlerware
import (
"github.com/go-redis/redis"
"../config"
)
var rc *redis.Client
func init() {
dsn := config.AppConfig.Redis.Host + ":" + config.AppConfig.Redis.Port
rc = redis.NewClient(&redis.Options{
Addr: dsn,
Password: config.AppConfig.Redis.Password,
})
Cont.Register("redis", rc)
}
f... |
package mapper
import (
"database/sql"
"github.com/fatih/structs"
"github.com/xormplus/xorm"
entity "mix/test/entity/cold"
"regexp"
"mix/test/utils/mysql"
)
func CreateDecryptionLog(session *xorm.Session, item *entity.DecryptionLog) (sql.Result, error) {
return session.SqlMapClient("CreateDecryptionLog", item... |
package deferred
import "fmt"
func Run(){
i:=1
defer fmt.Printf("deferred1 : %d\n",i)
i++
defer fmt.Printf("deferred2 : %d\n",i)
i++
fmt.Println(i)
} |
package router
import (
"context"
"fmt"
"net/http"
"os"
"runtime/debug"
"strconv"
"strings"
"boiler/pkg/entity"
"boiler/pkg/errors"
"boiler/pkg/store/config"
"github.com/go-chi/chi/middleware"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
"github.com/rs/zerolog/log"
)
// Recoverer ... |
package tools
import "github.com/json-iterator/go/extra"
func init() {
extra.RegisterFuzzyDecoders()
}
|
// 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... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-11-10 19:41
# @File : lt_713_Subarray_Product_Less_Than_K.go
# @Description :
# @Attention :
*/
package two_points
/*
排列组合问题: 计算相乘的积小于k的组合数的总和
双指针
左指针的每次移动,都需要将当前的值相除直到小于目标值之后右指针继续移动
*/
//
// func numSubarrayProductLessThanK(nums []int, k int) int {
//... |
package cmd
import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/spf13/cobra"
"github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/crypto/tmhash"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"strconv"
)
var blockTxsCmd... |
package sip
import (
"strings"
uriLib "github.com/superirale/sipserver/uri"
"github.com/superirale/sipserver/utils"
// "fmt"
)
// Authorization struct
type Authorization struct {
AuthType string
Username string
Realm string
Nonce string
Uri uriLib.URI
Response string
Algorithm string
isAu... |
package LatticeReduction
import (
"fmt"
"math/rand"
"testing"
)
var (
SmallBasisTest = Int64Basis{
[]int64{1, 1, 1},
[]int64{-1, 0, 2},
[]int64{3, 5, 6},
}
LargeBasisTest = SmallBasisTest.PremoteToBig()
)
const size = 35
func TestXx(t *testing.T) {
cases:=250
if testing.Short(){
cases=10
}
count:... |
package main
import (
"context"
"io/ioutil"
"log"
"net"
"os"
"time"
task "github.com/HarshVaragiya/LearningGo/Protobuf/gRPC/taskproto"
grpc "google.golang.org/grpc"
"google.golang.org/protobuf/proto"
)
var dataStore = "task-datastore.pb"
type taskServer struct {
}
func (s taskServer) List(ctx context.Cont... |
package util
import (
"sync"
"testing"
)
func TestWrite(t *testing.T) {
p := "/var/log/6ryim_test/6ryim_test.log"
w, err := NewWriter(p)
if err != nil {
t.Error(err)
}
defer w.Close()
var wg sync.WaitGroup
for i := 0; i <= 500; i++ {
go func() {
for k := 0; k < 10000; k++ {
_, err = w.Write([]byt... |
package resolvers
type Publication struct {
ID int `json:"id"`
Title string `json:"title"`
URI string `json:"uri"`
Date string `json:"date"`
}
var test1 = Publication{
ID: 01,
Title: "test title 1",
URI: "www.testuri1.com",
Date: "testdate1",
}
var test2 = Publication{
ID: 02,
Title: "tes... |
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) (float64, int) {
aproximation := func(z, x float64) float64 {
return z - ((z*z)-x)/(2*z)
}
i := 0
z := aproximation(1.0, x)
for math.Abs(aproximation(z, x)-z) > 0.000001 {
z = aproximation(z, x)
i++
}
return z, i
}
func main() {
for i := 1.... |
package galice
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestPing(t *testing.T) {
pingBody := `{
"meta": {
"locale": "ru-RU",
"timezone": "Europe/Moscow",
"client_id": "ru.yandex.searchplugin/5.80 (Samsung Galaxy; Android 4.4)",
"i... |
/*
Create a function that takes a integer number n and returns the formula for (a+b)^n as a string.
Examples
formula(0) ➞ "1"
formula(1) ➞ "a+b"
formula(2) ➞ "a^2+2ab+b^2"
formula(-2) ➞ "1/(a^2+2ab+b^2)"
formula(3) ➞ "a^3+3a^2b+3ab^2+b^3"
formula(5) ➞ "a^5+5a^4b+10a^3b^2+10a^2b^3+5ab^4+b^5"
Notes
Don't put the... |
// taken from https://code.google.com/p/wsdl-go
package main
import "encoding/xml"
type definitions struct {
XMLName xml.Name `xml:"definitions"`
TargetNamespace string `xml:"targetNamespace,attr"`
Name string `xml:"name,attr"`
Types xmlType `xml:"types"`
Messages []... |
package game
import (
"github.com/golang/glog"
"log"
"qipai/dao"
"qipai/utils"
"zero"
)
type handler func(s *zero.Session, msg *zero.Message)
type handlerWrap struct {
needAuth bool // 记录 是否需要授权后才能执行handler
handler handler
}
// 保存所有消息的处理函数
var handlers map[int32]handlerWrap = make(map[int32]handlerWrap)
//... |
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 gate
import "github.com/mi4tin/go-chassis-gate/filehelper"
var configObj *Config
//Config 是gate相关的一些配置
type Config struct {
//白名单
IPWhiteList string `yaml:"ipWhiteList"`
}
func init() {
initConfig()
}
//配置初始化
func initConfig() {
configObj = &Config{}
err := filehelper.GetConfig(configObj, filehelper.F... |
package handlers
import (
"net/http"
"strings"
"github.com/cloudfoundry-incubator/notifications/metrics"
"github.com/cloudfoundry-incubator/notifications/models"
"github.com/cloudfoundry-incubator/notifications/postal"
"github.com/ryanmoran/stack"
)
type NotifySpace struct {
errorWriter E... |
package link
import (
"os"
"testing"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/asm"
"github.com/cilium/ebpf/internal/testutils"
)
func TestSkLookup(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.8", "sk_lookup program")
prog := mustLoadProgram(t, ebpf.SkLookup, ebpf.AttachSkLookup, "")
netns, err :... |
// Copyright 2016 Jacques Supcik, HEIA-FR
//
// 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 a... |
package parens_test
import (
"errors"
"testing"
"github.com/spy16/parens"
"github.com/spy16/parens/parser"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func add(a, b float64) float64 {
return a + b
}
func BenchmarkParens_Execute(suite *testing.B) {
ins := parens.New(parens.Ne... |
package main
import (
"bufio"
"os"
"fmt"
"strconv"
)
var e_ map[int][]string
func e(n int) ([]string) {
if n == 0 {
return []string{""}
} else if _, exists := e_[n]; exists {
return e_[n]
}
e_[n] = make([]string, 0, 1)
i := 0
j := n - 1
for i < n {
for _, a := range e(i) {
for _, b := range e(j)... |
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag
package docs
import (
"bytes"
"encoding/json"
"strings"
"text/template"
"github.com/swaggo/swag"
)
var doc = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": ... |
package startup
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
)
/**
Structure to store all the configuration parameters
*/
type Parameters struct {
MaxQuestions int `json:"max_questions"`
Question... |
package util
import yaml "gopkg.in/yaml.v2"
// Convert converts the old object into the new object through json serialization / deserialization
func Convert(old interface{}, new interface{}) error {
o, err := yaml.Marshal(old)
if err != nil {
return err
}
if err := yaml.Unmarshal(o, new); err != nil {
return ... |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-04 08:59
* Description:
*****************************************************************/
package main
import (
"fmt"
"github.com/go-xe2/xthrift... |
package Service
import (
"Work_5/DAO"
"Work_5/object"
)
//提问方法
func PutQuestion(user *object.User, question *object.Question) object.ErrMessage {
//获取数据库连接
db, err := DAO.DataBaseInit()
if err.IsErr {
return err
}
//查询用户是否存在
isexist, _ := DAO.UserQuery(user, db)
if !isexist {
err.IsErr = true
err.Wha... |
package main
import (
"os"
"text/template"
)
var tmpl = template.Must(template.New("hello").Parse(`Hello from {{ . }}`))
func main() {
err := tmpl.Execute(os.Stdout, "go templates!")
if err != nil {
panic(err)
// NOTE: This error is not reachable in this example
}
}
|
package orders
import (
"Pinjem/businesses/orders"
"context"
"time"
"gorm.io/gorm"
)
type OrderRepository struct {
Conn *gorm.DB
}
func NewOrderRepository(conn *gorm.DB) orders.DomainRepository {
return &OrderRepository{Conn: conn}
}
func (b *OrderRepository) GetAll(ctx context.Context) ([]orders.Domain, err... |
package service
import (
"context"
"github.com/koind/cacher/internal/domain/repository"
)
// Сервис кэша
type CacheService struct {
cacheRepository repository.CacheRepositoryInterface
}
// Создает новый сервис кэша
func NewCacheService(cr repository.CacheRepositoryInterface) *CacheService {
return &CacheService{... |
package calculator
import (
"fmt"
"strconv"
"strings"
)
type stack struct{ vec []string }
func (s stack) Empty() bool { return len(s.vec) == 0 }
func (s *stack) Push(str string) { s.vec = append(s.vec, str) }
func (s *stack) Pop() string {
d := s.vec[len(s.vec)-1]
s.vec = s.vec[:len(s.vec)-1]
return d
}
... |
package postgres
import (
"context"
core "github.com/Qalifah/aboki-africa-assessment"
)
type TransactionRepository struct {
client *Client
}
func NewTransactionRepository(client *Client) *TransactionRepository {
return &TransactionRepository{
client: client,
}
}
func(t *TransactionRepository) CreateTransact... |
package main
import (
"fmt"
"testing"
)
func TestGouYouTuan(t *testing.T) {
err := Init()
if err != nil {
t.Fatal(err)
}
err = catchGouYouTuan()
if err != nil {
t.Fatal(err)
}
news, err := getNews()
if err != nil {
t.Fatal(err)
}
fmt.Println(news)
}
func TestGolangTC(t *testing.T) {
err := Init... |
package remark
import (
"net/http"
ctl "github.com/go-jar/gohttp/controller"
"blog/controller/api"
"blog/svc/remark"
)
type RemarkContext struct {
*api.ApiContext
remarkSvc *remark.Svc
}
func (c *RemarkContext) BeforeAction() {
c.ApiContext.BeforeAction()
c.remarkSvc = remark.NewSvc(c.TraceId)
}
type Re... |
package backend
import (
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
}}
|
// This file was generated for SObject UserProvAccountStaging, API Version v43.0 at 2018-07-30 03:47:54.639201989 -0400 EDT m=+40.983346230
package sobjects
import (
"fmt"
"strings"
)
type UserProvAccountStaging struct {
BaseSObject
ConnectedAppId string `force:",omitempty"`
CreatedById string `force:"... |
package main
import (
"fmt"
"errors"
)
//关键字 func 、函数名、参数列表、返回值、函数体和返回语句。
//返回值被命名之后,它们的值在函数开始的时候被自动初始化为空
func Add(a,b int) (ret int,err error) {
if a<0 || b<0{
//fmt.Println(err)
//err 早就被初始化未 类型零值
err = errors.New("Should be non-negative nums")
return
}
return a+b,nil
}
//不定参数类型 被接收成为一个slice
// ...t... |
package main
import "fmt"
func main() {
x :=make(map[string]int)
q :=make([]int,3)
x["a"]=3
x["c"]=4
q[0]=7
q[1]=4
q[2]=3
fmt.Println(x)
fmt.Println(q)
}
|
/*
(Lattice Paths)
Starting in the top left corner of a 2x2 grid, there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 20x20 grid?
*/
package main
import (
"fmt"
)
func main() {
// Justification:
// You have to make 40 steps to get from top-left to bottom-right... |
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"log"
"net/http"
"os"
)
var RechargeSercice string
func init() {
RechargeSercice = BuildServiceUrlPrefixFromEnv("CouponSercice", false, os.Getenv("ENV_NAME_DATAFOUNDRYCOUPON_SERVICE_HOST"), os.Getenv("ENV_NAME_DATAFOUNDRYCOUPON_SERVICE_PORT"))
}
func... |
package auth
import (
"context"
"github.com/google/uuid"
"github.com/spf13/viper"
"net/http"
)
type userCtx struct{}
func GuestSession(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
tokenName := viper.GetString("oauth.sessionCookie.name")
_, err... |
package main
import (
"bytes"
"crypto/sha1"
"errors"
"flag"
"fmt"
"io"
"log"
"math"
"math/rand"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/rakoo/rakoshare/pkg/id"
"github.com/rakoo/rakoshare/pkg/sharesession"
ed "github.com/agl/ed25519"
"github.com/nictuku/dht"
"github.com/zeebo/bencode"
)
... |
package api
import (
"time"
"github.com/google/uuid"
)
type NewBusinessRequest struct{
BusinessName string `json:"business_name" binding:"required"`
BusinessURI string `json:"business_uri" binding:"required"`
Metadata map[string]interface{} `json:"metadata"`
... |
package main
import (
"fmt"
)
// channels block i.e. any send(or receive) in the channel blocks the further execution of
// go-routine until another go-routing is receiving(or sending) data from the channel
// like here, main1() will not work, as on channel, 42 is being written(send), but there's
// no go-routine... |
package main
import (
"gopkg.in/jdkato/prose.v2"
"fmt"
"math/rand"
"time"
)
var dataFileLoc string = "data/dataset.json"
var typeFileLoc string = "data/types.json"
var submissionFileLoc string = "output.json"
func main() {
start := time.Now()
defer fmt.Println(time.Since(start))
fmt.Println("Process begins\n"... |
package bridge
import (
"errors"
"go.uber.org/zap"
"rocketmqtt/conf"
"strings"
)
const (
Kafka = iota
Rocketmq
)
var Delivers deliver
type PublishMessage interface {
publish(topics map[string]bool, key string, msg *Elements) error
}
type deliver struct {
rocketMQClients map[string]*rocketMQ
kafkaClients ... |
package config
import (
"reflect"
"github.com/bonjourmalware/melody/internal/tagparser"
)
// LoadYAMLTagsOf loads the yaml tags of a struct
func LoadYAMLTagsOf(what interface{}) ([]string, error) {
var tags []string
for i := 0; i < reflect.TypeOf(what).NumField(); i++ {
ruleTag := reflect.TypeOf(what).Field(i... |
package main
import (
"fmt"
"time"
)
// go routineによるセマフォの実装パターンを試す
// 最大入室5人までチャットルームでログイン中ユーザと総数を出す
const (
maxConcurrency int = 5
jobsize int = 500
)
var (
doneIds chan string = make(chan string, jobsize)
nowloginIDs chan string = make(chan string, jobsize)
sem chan struct{} = make(c... |
package model
import (
"html/template"
"time"
)
type HomePageData struct {
Articles []Article `json:"articles"`
}
type Article struct {
tableName struct{} `sql:"articles,alias:article"`
ID int64 `json:"id" sql:",pk"`
Title string `json:"title" sql:",notnull"`
Author ... |
package databroker_test
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/pomerium/pomerium/pkg/grpc/... |
/**
* @Author: XGH
* @Email: 55821284@qq.com
* @Date: 2020/5/14 14:00
*/
package main
import "testing"
func TestAli(t *testing.T) {
type args struct {
str string
}
tests := []struct {
name string
args args
want bool
}{
{
name: "支付宝测试",
args: args{str: ""},
want: true,
},
}
for _, tt := ra... |
package etcd
import (
"fmt"
"testing"
"golang.org/x/net/context"
"github.com/zdao-pro/sky_blue/pkg/naming"
"go.etcd.io/etcd/clientv3"
)
func TestRegister(t *testing.T) {
c := clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
}
b, err := New(&c)
if nil != err {
fmt.Println(err.Error())
}
in := n... |
// Package main applies a transform.Transformation to a geometry.Point with more
// documentation from the help flag.
package main
import (
"errors"
"fmt"
"os"
"github.com/jwowillo/viztransform/cmd"
"github.com/jwowillo/viztransform/parse"
"github.com/jwowillo/viztransform/transform"
)
// main applies the tran... |
package main
import "fmt"
func main() {
var x, y int
fmt.Scanf("%d.%d", &x, &y)
fmt.Printf("%d.%d\n", y, x)
}
|
package config
import (
"time"
"github.com/kelseyhightower/envconfig"
)
// Config represents the configuration required for florence
type Config struct {
BindAddr string `envconfig:"BIND_ADDR"`
APIRouterURL string `envconfig:"API_ROUTER_URL"`
APIRouterVersion ... |
package main
import "fmt"
// 647. 回文子串
// 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
// 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
// 注意:
// 输入的字符串长度不会超过1000。
// https://leetcode-cn.com/problems/palindromic-substrings/
func main() {
fmt.Println(countSubstrings("aaa")) // 6
fmt.Println(countSubstrings("abc")) // 3
fmt... |
package main
import (
"fmt"
"log"
"golang.org/x/sys/windows/registry"
)
func main() {
instDir := getInstallationDir()
defaultFontPath := fontName + ".ttf"
defaultOverviewDirectory := "./overviews/"
if instDir != "" {
defaultFontPath = fmt.Sprintf("%v\\%v.ttf", instDir, fontName)
defaultOverviewDirectory =... |
package timecop_test
import (
"github.com/bluele/go-timecop"
"testing"
"time"
)
func TestFreeze(t *testing.T) {
now := timecop.Now()
timecop.Freeze(now)
if timecop.Now() != now {
t.Errorf("Expected time is not %v.", now)
}
timecop.Return()
if !timecop.Now().Before(time.Now()) {
t.Error("timecop should... |
package main
import (
"LogDemo/Utils"
"LogDemo/conf"
"LogDemo/etcd"
"LogDemo/kafka"
"LogDemo/taillog"
"fmt"
"gopkg.in/ini.v1"
"sync"
"time"
)
var (
cfg = new(conf.AppConf)
)
func main() {
// 加载配置文件
err := ini.MapTo(&cfg, "./conf/config.ini")
if err != nil {
fmt.Printf("load ini failed, err: %v \n", e... |
package kafka
import (
"context"
"crypto/tls"
"fmt"
"github.com/Shopify/sarama"
"github.com/cloudevents/sdk-go/protocol/kafka_sarama/v2"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/pkg/errors"
skafka "github.com/segmentio/kafka-go"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
... |
// 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 shell
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHelpNameShouldReturnHelp(t *testing.T) {
assert.Equal(t, "help", help(0).name())
}
func TestHelpsDescriptionShouldNotBeEmpty(t *testing.T) {
assert.NotEqual(t, "", help(0).description())
}
func TestHelpUsageShouldNotBeEmpty(t *tes... |
package datastructures
// Stack operations
type Stack interface {
IsEmpty() bool
Peek() interface{}
Push(value interface{})
Pop() interface{}
String() string
}
|
package venti
import (
"errors"
venti "sigint.ca/venti2"
)
type Backend interface {
ReadBlock(venti.Score, []byte) (int, error)
WriteBlock(typ uint8, data []byte) (venti.Score, error)
}
var (
ENotFound = errors.New("block not found")
)
type MemBackend map[venti.Score][]byte
func (b MemBackend) ReadBlock(s ve... |
package cli
import (
"io/ioutil"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
"github.com/ch3lo/overlord/configuration"
"github.com/ch3lo/overlord/logger"
"github.com/ch3lo/overlord/version"
"github.com/codegangsta/cli"
)
var config *configuration.Configuration
func globalFlags() []cli.Flag {
flags := []cli.Fl... |
package main
import "fmt"
//1.下面的代码输出什么?
func main() {
var a []int = nil
//a = []int{1, 2}
a, a[0] = []int{1,2}, 9
fmt.Println(a)
}
//参考答案即解析:运行时错误。知识点:多重赋值。
//
//多重赋值分为两个步骤,有先后顺序:
//2.下面代码中的指针 p 为野指针,因为返回的栈内存在函数结束时会被释放?
//type TimesMatcher struct {
// base int
//}
//
//func NewTimesMatcher(base int) *TimesMatc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.