text stringlengths 11 4.05M |
|---|
package concurrent
import (
"errors"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestMerge(t *testing.T) {
t.Run("empty", func(t *testing.T) {
require.NoError(t, Merge(nil, nil))
})
t.Run("with nil", func(t *testing.T) {
require.NoError(t, Merge([]FuncWithResultMayError{nil}, nil))
})
... |
package main
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"net"
"os"
"../gen/pb"
"github.com/golang/protobuf/proto"
)
//channel 只声明不make 使用是会出问题的
//var quitSemaphore chan bool
var (
quitSemaphore = make(chan bool)
name string
)
func main() {
//先创建addr
var tcpAddr *net.TCPAddr
tcpAddr, _ = net.Resolve... |
package str
import (
"fmt"
"testing"
)
func TestMyAtoi(t *testing.T) {
fmt.Println(MyAtoi("42"))
}
func MyAtoi(str string) int {
first := 0
for i := 0; i < len(str); i++ {
if str[i] != ' ' {
first = i
break
}
}
str = str[first:]
if len(str) == 0 {
return 0
}
if str[0] == '-' || (str[0] >= '0... |
package tasks
/*
type TaskInfo struct {
TaskId string `json:"task_id"`
TaskType string `json:"task_type"`
TaskName string `json:"task_name"`
DataType string `json:"data_type"`
Status string `json:"status"`
Progress string `json:"progress"`
Process string `json:"process"`
StartT... |
package zoro
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
"unicode"
"github.com/anaskhan96/soup"
)
func GetPageDescriptionForZoro(productUrls []string) [][]interface{} {
var finalValues [][]interface{}
loc, _ := time.LoadLocation("America/Bogota")
currentTime := time.N... |
package utils
import (
"bufio"
"fmt"
"os"
"time"
)
var Logchannel = make(chan map[string]string, 2000) //缓冲区数据对象存储
//使用缓冲区日志
func LogInfo(content string) {
//判断文件是否存在
mp := make(map[string]string)
mp["date"] = string(time.Now().Format("2006-01-02 15:04:05"))
mp["content"] = content
Logchannel <- mp
}
//创建日志接口... |
package middleware
import (
"log"
"net/http"
"time"
)
//Middleware 타입은 모든 미들웨어 함수가 리턴하는 함수 타입이다.
type Middleware func(http.HandlerFunc) http.HandlerFunc
//ApplyMiddleware 함수는 모든 미들웨어를 적용할 것이고,
//마지막 인자는 컨텍스트를 전달하기 위한 목적으로 사용된
//바깥쪽의 래퍼이다.
func ApplyMiddleware(h http.HandlerFunc, middleware ...Middleware) http.Han... |
package main
import (
"fmt"
"github.com/stretchr/testify/assert"
"math/rand"
"testing"
)
func TestNotationRollFromString(t *testing.T) {
result1, err1 := NotationRollFromString("1+6")
assert.Nil(t, err1)
assert.Equal(t, *result1, roll{1, 6})
_, err2 := NotationRollFromString("1 2")
assert.NotNil(t, err2)
... |
package k8s
import (
"context"
"log"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/discovery"
memory "k8s.io/client-go/discovery/cached"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"k8s.io/client-... |
//aws_export_vpc.go
package main
import (
"fmt"
)
func aws_export_vpc(region string, environment string) {
//fmt.Println("Exporting AWS vpc in region: " + region + " for environment: " + environment)
if check_aws_initialized() == true {
if get_environment_state(environment,region) != "initialized" {
i... |
package customer
type ReceiptListReq struct {
StartTime string `description:"起始时间"`
EndTime string `description:"结束时间"`
BankID int64 `description:"银行ID"`
ShopID int64 `description:"店铺ID"`
ReceiptType string `description:"收支类型ID"`
Search string `description:"搜索"`
BillType int64 `descri... |
package responses
import "time"
type Employee struct {
ID uint
CreatedAt time.Time
UpdatedAt time.Time
Name string
Description string
OriginName string
}
|
package collector
import (
"math"
"strconv"
"time"
"strings"
"github.com/andrewn3wman7/statuscake-exporter/stk"
"github.com/prometheus/client_golang/prometheus"
)
type stkSSLCollector struct {
StkAPI *stk.StkAPI
stkSslUp *prometheus.Desc
stkSslCertScore *prometheus.Desc
st... |
package format
import (
"strings"
"github.com/g-harel/gothrough/internal/types"
)
func formatDocs(docs *types.Docs) *Snippet {
snippet := NewSnippet()
if docs.Text == "" {
return snippet
}
docLines := strings.Split(strings.TrimSpace(docs.Text), "\n")
if len(docLines) < 1 {
return snippet
}
for _, lin... |
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "... |
package util
import "os"
// GetenvRequired returns the environment variable key.
// If it is not defined, panics the application.
func GetenvRequired(key string) string {
val := os.Getenv(key)
if val == "" {
panic("Variable `" + key + "` is required, please set it in `.env` file.")
}
return val
}
|
package main
import (
Reverse "../reverse"
"fmt"
)
// Package level variable
var x int = 0
func main() {
fmt.Println(x)
fmt.Println(Reverse.MyName)
fmt.Println(Reverse.Add(1, 2))
}
|
package main
import "github.com/panupongdeve/gin-web-start/app"
func main() {
app.Start()
}
|
// Source : https://oj.leetcode.com/problems/search-insert-position/
// Author : Austin Vern Songer
// Date : 2016-04-28
/**********************************************************************************
*
* Given a sorted array and a target value, return the index if the target is found.
* If not, return the index... |
package main
type Entity struct {
Row1 string
Row2 string
Row3 string
Row4 string
}
type Entities []Entity
|
package models
import (
"github.com/astaxie/beego/orm"
"time"
)
func (a *SpiderCoinMarket) TableName() string {
return SpiderCoinMarketTBName()
}
//货币行情数据
type SpiderCoinMarket struct {
Coin string `orm:"pk;column(coin)"json:"coin"form:"coin"`
//区块儿奖励
BlockReward string `json:"block_reward"`
//出块儿时间[秒]
Block... |
package venom
import "testing"
func Test_RemoveNotPrintableChar(t *testing.T) {
type args struct {
in string
}
tests := []struct {
name string
args args
want string
}{
{
name: "remove U+001B escape code (not printable)",
// line below contains escapce code U+001B
args: args{in: "python-mysqldb ... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseOptions(t *testing.T) {
h, err := NewAwsS3ReverseProxy(Options{
AllowedSourceEndpoint: "foobar.endpoint.example.com",
AllowedSourceSubnet: []string{"127.0.0.1/32", "192.168.1.0/24"},
AwsCredentials: []string{"foooo... |
package main
import (
"fmt"
"github.com/golang/protobuf/proto"
"github.com/smallgamefish/BreakBricks/game"
"github.com/smallgamefish/BreakBricks/protoc/github.com/smallgamefish/BreakBricks/protoc"
"log"
"net"
)
const (
//最大的消息长度,默认是512字节
//1Byte(字节) = 8bit(位)
//1KB = 1024Byte(字节)
//1MB = 1024KB
//1GB = 102... |
package delivery
import (
"HttpBigFilesServer/MainApplication/config"
"HttpBigFilesServer/MainApplication/internal/files/model"
"HttpBigFilesServer/MainApplication/pkg/logger"
"io"
"mime/multipart"
"net/http"
"os"
"strconv"
)
func MultiPart(filename string, pW *io.PipeWriter, fd *os.File, l logger.Interface, ... |
package models
import (
"fmt"
"strings"
"github.com/astaxie/beego"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var DB *gorm.DB
func LoadDB() error {
mUser := beego.AppConfig.String("mysqluser")
mPass := beego.AppConfig.String("mysqlpass")
mDB := beego.AppConfig.String("mysqlDB")
co... |
package main
import (
"digileaps/user/config"
"digileaps/user/entities"
"digileaps/user/model"
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2/bson"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/user/findall", FindAllAPI).Methods("GET")
r.HandleFunc("/api/user/find/{i... |
package job
import (
"github.com/gin-gonic/gin"
"net/http"
"yj-app/app/model"
jobModel "yj-app/app/model/monitor/job"
jobLogModel "yj-app/app/model/monitor/job_log"
jobService "yj-app/app/service/monitor/job"
jobLogService "yj-app/app/service/monitor/job_log"
userService "yj-app/app/service/system/user"
"yj-a... |
package models
type FmtSmsSendLog struct {
LogId int64 `gorm:"column:msg_id"` // id
TaskId string `gorm:"column:task_id"` // 任务ID
TemplateId string `gorm:"column:template_id"` // 模板ID
Phone string `gorm:"column:phone"` // 手机号
Status int `gorm:"column:status"` ... |
package main
import (
"database/sql"
"log"
"net/http"
"./controllers"
"./driver"
"./utils"
"github.com/subosito/gotenv"
"github.com/gorilla/mux"
)
var db *sql.DB
func init() {
gotenv.Load()
}
func main() {
db = driver.ConnectionDB()
controller := controllers.Controller{}
router := mux.NewRouter()
... |
package domain
import "github.com/google/uuid"
type MatrixRepository interface {
Matrix(id uuid.UUID) (Matrix, error)
Matrices() ([]Matrix, error)
CreateMatrix(matrix *Matrix) error
UpdateMatrix(matrix *Matrix) error
DeleteMatrix(id uuid.UUID) error
AddSubject(matrixSubject *MatrixSubject) error
RemoveSubject(... |
package boltdb
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"os"
"strconv"
"github.com/Mrcampbell/pgo2/breed-service/app"
"github.com/Mrcampbell/pgo2/protorepo/pokemon"
"github.com/boltdb/bolt"
)
func (bs *BreedService) load() error {
breedList := make(map[string]pokemon.BreedDetail, 0)
err := loadCSVBase(b... |
package main
import (
"bufio"
"bytes"
"encoding/csv"
"strconv"
"strings"
)
const (
ADMIN_USERS_UNKNOWN_SUBCOMMAND = "Unknown subcommand"
ADMIN_USERS_USER_ID_SHOULD_BE_SPECIFIED = "USER ID should be specified"
ADMIN_USERS_ID_SHOULD_BE_INTEGER = "Sorry. Users id's should be integers"
ADMIN_USER... |
package config
import "github.com/odpf/salt/config"
func Load(configFile string) (Config, error) {
var cfg Config
loader := config.NewLoader(config.WithFile(configFile))
if err := loader.Load(&cfg); err != nil {
return Config{}, err
}
return cfg, nil
}
|
/**
* Tencent is pleased to support the open source community by making polaris-go available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may o... |
/*
description :
ex0107 is a variation on the fetch program
author :
Tom Geudens (https://github.com/tomgeudens/)
modified :
2017/07/24
*/
package main
import "fmt"
import "io"
import "net/http"
import "os"
func main() {
// loop through arguments (which should be urls)
for _, url := range os.Args[1:] {
//... |
// Package services a collection of objects which normalize functions from models and third party
// apis with the intent of providing data to providers.
package services
|
package huma
import (
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/andybalholm/brotli"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestRecoveryMiddleware(t *testing.T) {
r := NewTestRouter(t)
r.GinEngine().Use(Recovery())
r.... |
package gannettApi
import (
"os"
"testing"
)
type ArticleIdTestCase struct {
Url string
Id int
}
func getApiKey(t *testing.T) string {
key := os.Getenv("GANNETT_ASSET_API_KEY")
if key == "" {
t.Fatalf("GANNETT_ASSET_API_KEY is required")
}
return key
}
func TestArticleScrapingNoPhotoOrVideo(t *testing.T)... |
package store
// Store
type Store interface {
User() UserRepository
} |
package main
import (
"flag"
"fmt"
"os"
"github.com/hackebrot/amelia/amelia"
)
var description string
var public bool
func init() {
const (
dDefault = "Amelia Gist"
dUsage = "description of the gist"
)
flag.StringVar(&description, "description", dDefault, dUsage)
flag.StringVar(&description, "d", dDef... |
package device
// #cgo CFLAGS: -g -Wall
// #cgo LDFLAGS: -lSoapySDR
// #include <stdlib.h>
// #include <stddef.h>
// #include <SoapySDR/Device.h>
// #include <SoapySDR/Formats.h>
// #include <SoapySDR/Types.h>
import "C"
import "unsafe"
/* ******************************************************************************... |
// Copyright 2020 Paul Greenberg greenpau@outlook.com
//
// 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 applic... |
/*
* outer: outer product
*
* input:
* vector: a vector of (x, y) points
* nelts: the number of points
*
* output:
* matrix: a real matrix, whose values are filled with inter-point
* distances
* vector: a real vector, whose values are filled with origin-to-point
* distances
*/
package main
... |
/*
Copyright (C) 2019 Expedia Group.
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, software
... |
// This file is taken from https://github.com/mongodb/mongo-go-driver
// and its `internal/testutil/assert` package.
package assert
import (
"reflect"
"sync"
"testing"
"github.com/google/go-cmp/cmp"
)
var cmpOpts sync.Map
var errorCompareFn = func(e1, e2 error) bool {
if e1 == nil || e2 == nil {
return e1 ==... |
package authentication
import (
"fmt"
"log"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo"
)
func CreateToken(c echo.Context, username string) string {
claims := jwt.MapClaims{
"username": username,
// UserCond data
"expiry": time.Now().Add(time.H... |
package main
import (
"fmt"
)
type Graph struct {
DataInfo string
Data map[interface{}][]interface{}
DataComma string
NodesArrayInfo string
Nodes []interface{}
}
type gph *Graph
func InitGraph(node interface{}) *Graph {
d := make(map[interface{}][]interface{});
c := make([]interface{}, 0);
b :=... |
package app
import (
pb "github.com/chenzhe84/BaiCloud/metadata-service/proto/app"
"github.com/jinzhu/gorm"
)
type IRepository interface {
SaveApp(*pb.App) error
GetAppById(string) (*pb.App, error)
SaveModule(*pb.Module) error
GetModuleById(string) (*pb.Module, error)
SaveForm(*pb.Form) error
GetFormById(stri... |
package main
import (
"fmt"
"sync"
)
// 变量
var a = 1
// 会话一
func sessionAdd() {
for i := 0; i < 100; i++ {
a += i
}
}
// 会话二
func sessionSub() {
for i := 0; i < 100; i++ {
a -= i
}
}
// 会话三
func sessionPrint() {
fmt.Println(a)
}
func main() {
var wg = new(sync.WaitGroup)
wg.Add(3)
go func() {
defe... |
package sqs
import awsSQS "github.com/aws/aws-sdk-go/service/sqs"
// Queue interface has the same signature as the methods in SQS struct in aws-sdk-go.
// Holds only the messages we're interested in pubsub.
type Queue interface {
ReceiveMessage(*awsSQS.ReceiveMessageInput) (*awsSQS.ReceiveMessageOutput, error)
Dele... |
package main
import (
"Open_IM/internal/rpc/friend"
"flag"
)
func main() {
rpcPort := flag.Int("port", 10200, "get RpcFriendPort from cmd,default 12000 as port")
flag.Parse()
rpcServer := friend.NewFriendServer(*rpcPort)
rpcServer.Run()
}
|
// Copyright (c) 2018 Aiven, Helsinki, Finland. https://aiven.io/
package aiven
import (
"fmt"
"strings"
"github.com/aiven/aiven-go-client"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
var aivenProjectUserSchema = map[string]*schema.Schema{
"project": {
Description: "The project the user belong... |
package gencoder_test
import (
"testing"
"github.com/bgokden/veri/data/gencoder"
"github.com/stretchr/testify/assert"
)
func TestDatumScoreEncoding(t *testing.T) {
ds := gencoder.DatumScore{Score: 3}
b, e := ds.Marshal()
assert.Nil(t, e)
ds2 := gencoder.DatumScore{Score: 0}
_, e2 := ds2.Unmarshal(b)
assert.... |
package server
import (
"fmt"
"net/http"
"os"
"github.com/kevinwubert/fb-messenger-analysis/pkg/message"
"github.com/kevinwubert/fb-messenger-analysis/pkg/visualizer"
"github.com/pkg/errors"
)
func Main() error {
args := os.Args
if len(args) != 2 {
return errors.New("invalid number of arguments.\ncommand f... |
package pointers
import (
"fmt"
"testing"
)
type Vertex struct {
X int
Y int
}
func TestFunction(t *testing.T) {
p := Vertex{1, 2}
q := &p
q.X = 1e9
fmt.Println(p)
q.X++
}
|
package stackdriver
import (
"context"
"errors"
"log"
"strings"
"cloud.google.com/go/logging"
)
//StackdriverNotifier ...
type StackdriverNotifier struct {
ProjectName string
LogID string
client *logging.Client
logger *logging.Logger
}
//Create a notifier
func (s *StackdriverNotifier) Creat... |
package main
//Take the code from the previous exercise, then store the values of type person in a map with the key of first name. Access each value in the map. Print out the values, ranging over the slice.
import (
"fmt"
)
type person struct {
first, last string
favFlavours []string
}
func main() {
pers1 := pe... |
package redis_test
import (
"github.com/sundogrd/content-api/utils/redis"
"testing"
)
// go test -run="NoopsGetContentListWithFilter"
func TestInitRedis(t *testing.T) {
err := redis.Init(1)
if err != nil {
t.Fatal(err)
}
// t.Log(resp)
// realResp := resp.RealResponse().(*noops.GetContentListWithFilterRespon... |
package msgHandler
func (tdm *TDMMsgHandler) AllRoutineExitWg() {
tdm.allRoutineExitWg.Wait()
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/12/7 9:21 下午
# @File : lt_5_最长回文字符串.go
# @Description :
# @Attention :
*/
package hot100
//
// func longestPalindrome(s string) string {
//
// }
|
package main
import (
"testing"
"github.com/jackytck/projecteuler/tools"
)
func TestP66(t *testing.T) {
cases := []tools.TestCase{
{In: 1000, Out: 661},
}
tools.TestIntInt(t, cases, solve, "P66")
}
|
package main
import (
"fmt"
"strings"
)
const (
MESSAGE_TEXT_IS_DEFAULT = "You have default message text"
MESSAGE_TEXT_IS_CUSTOM = "Your message text: %s"
MESSAGE_SUCCESSFUL = "Message text is set.\nSample response: %s"
MESSAGE_TEXT_IS_RESET = "Message text is reset to default"
MESSAGE_INCO... |
// Copyright 2012 The go-gl 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 gltest
import (
"log"
"runtime"
"sync"
"time"
"github.com/go-gl/gl"
"github.com/go-gl/glfw"
)
var main_thread_setup = make(chan func())
var ... |
package sfcli
import (
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/urfave/cli"
"github.com/solidfire/solidfire-docker-driver/sfapi"
"strings"
"unicode/utf8"
)
var client, _ = sfapi.New()
// cmdNofFound routines borrowed from rackspace/rack
// https://github.com/rackspace/rack/blob/master/commandsuggest.... |
/*
Description
You work for an art store that has decided to carry every style and size of drafting triangle in existence. Unfortunately, sorting these has become a problem. The manager has given you the task of organizing them. You have decided to classify them by edge length and angles. To measure each triangle, yo... |
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"net/http"
netUrl "net/url"
"regexp"
"runtime"
"strings"
"github.com/corneldamian/httpway"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/kataras/hcaptcha"
"golang.org/x/crypto/bcrypt"
)
var errAlreadySetUp = errors.New("alre... |
package logging
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/apache/arrow/go/v8/arrow"
"github.com/google/uuid"
"github.com/apache/arrow/go/v8/arrow/array"
"github.com/apache/arrow/go/v8/parquet"
"github.com/apache/arrow/go/v8/parquet/pqarrow"
)
type FileLogSink struct {
... |
package usergroup
import (
"context"
"encoding/json"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/go-playground/validator/v10"
"github.com/hardstylez72/bblog/ad/pkg/util"
"net/http"
)
type Pair struct {
GroupId int `json:"groupId" validate:"required"`
UserId int `json:"userId" validate:"re... |
package util
import "github.com/Masterminds/goutils"
// Abbr abbreviated the s by verbose to maxWidth.
// verbose == 0 return ""
// verbose == 1 return max(s, maxWidth)
// verbose == 2 return full s
// others return "".
func Abbr(s string, verbose, maxWidth int) string {
switch verbose {
case 2: // nolint:gomnd
r... |
package store
import (
"testing"
"github.com/go-pg/pg"
"github.com/google/uuid"
"github.com/gracew/widget/graph/model"
"github.com/stretchr/testify/assert"
)
func TestNewAPI(t *testing.T) {
db := pg.Connect(&pg.Options{User: "postgres"})
defer db.Close()
s := Store{DB: db}
name := uuid.New().String()
inpu... |
package main
import (
"io"
"net"
"fmt"
"net/http"
"strconv"
"encoding/json"
"io/ioutil"
"bytes"
)
type clientConnection struct {
connection net.Conn
port int
playerInfo connectionPlayerInfo
}
type connectionPlayerInfo struct {
apptoken int
Id string `json:"id"`
Nickname string `json:"nickname"`
Games... |
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package main
import "fmt"
func factorialRecursive(value int) int {
if value == 1 {
return 1
} else {
return value * factorialRecursive(value-1)
}
}
func main() {
// function recursive adalah , pemanggilan function dirinya sendiri di dalam function dirinya
result := factorialRecursive(5)
fmt.Pr... |
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/kpacha/load-test/db"
"github.com/kpacha/load-test/requester"
_ "github.com/kpacha/load-test/statik"
"github.com/rakyll/statik/fs"... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
config := LoadConfig()
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
text, err := reader.ReadString('\n')
if err == io.EOF {
fmt.Printf("exit\n")
os.Exit(0)
}
tokens := strings.Split(strings.TrimSpace(text), "... |
package stub
import (
"fmt"
"github.com/sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
type s3Input struct {
s3Svc *s3.S3
bucketName, region, namespace s... |
package model
import (
"errors"
"time"
database "../database"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
)
// User model
type User struct {
ID string `gorm:"column:id;type:varchar(50);primary_key;not null;"`
Mobile string `gorm:"column:mobile;type:varchar(20);"`
Email st... |
package mapio
import (
"github.com/gorilla/mux"
"log"
"net/http"
"strings"
)
type httpmethod string
//Http methods for creating routes
const (
GET httpmethod = "GET"
POST httpmethod = "POST"
PUT httpmethod = "PUT"
DELETE httpmethod = "DELETE"
HEAD httpmethod = "HEAD"
)
//A "path" specification
ty... |
package main
import (
"github.com/abiosoft/ishell"
)
func main() {
// create new shell.
// by default, new shell includes 'exit', 'help' and 'clear' commands.
shell := ishell.New()
shell.AddCmd(&ishell.Cmd{
Name: "login",
Func: func(c *ishell.Context) {
c.ShowPrompt(false)
defer c.ShowPrompt(true)
... |
package svc
import (
"blog/resource/log"
)
type BaseSvc struct {
TraceId []byte
}
func (bs *BaseSvc) DebugLog(point, msg []byte) {
log.AccessLogger.Debug(log.FormatAccessLog(bs.TraceId, point, msg))
}
func (bs *BaseSvc) InfoLog(point, msg []byte) {
log.AccessLogger.Info(log.FormatAccessLog(bs.TraceId, point, ms... |
package main
import "fmt"
/*
Using newly learned doc string
and using func init() to initialize a map
before func main() execution
*/
var globalMap map[string]string
func init() {
globalMap = make(map[string]string)
globalMap["benchmark"] = "Fran"
}
func main() {
fmt.Println(globalMap) //it is already non-empty... |
package handlers
import (
"net/http"
"github.com/ONSdigital/dp-api-audit-spike/auditing"
"github.com/ONSdigital/go-ns/audit"
"github.com/ONSdigital/go-ns/common"
"github.com/fatih/color"
"github.com/gorilla/mux"
)
var greenOut = color.New(color.FgHiGreen)
func Foo(auditor audit.AuditorService) http.Handler {
... |
package testing
import "github.com/devspace-cloud/devspace/pkg/devspace/config/generated"
// Loader is a fake implementation of the ConigLoader interface
type Loader struct {
Config generated.Config
}
// Load is a fake implementation o this function
func (l *Loader) Load() (*generated.Config, error) {
return &l.Co... |
package main
import (
"fmt"
"github.com/bcampbell/fuzzytime"
)
func main() {
inputs := []string{
"Wed Apr 16 17:32:51 NZST 2014",
"2010-02-01T13:14:43Z", // an iso 8601 form
"no date or time info here",
"Published on March 10th, 1999 by Brian Credability",
"2:51pm",
"6/10/2021, 8:26:03 AM",
}
for _... |
// Copyright 2012 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.
package truetype
// The Truetype opcodes are su... |
package controllers
import (
"fmt"
"net/http"
"io/ioutil"
"strconv"
"encoding/json"
"commontest/Test"
"commontest/Config"
"commontest/Result"
"github.com/gorilla/mux"
"github.com/tealeg/xlsx"
)
type ResultContr struct {
conf *Config.Config
}
func NewResultController(c *Config.Config) *ResultContr {
gen :... |
package services
import (
guuid "github.com/google/uuid"
"github.com/rezwanul-haque/ID-Service/src/domain/companies"
"github.com/rezwanul-haque/ID-Service/src/domain/users"
"github.com/rezwanul-haque/ID-Service/src/utils/consts"
"github.com/rezwanul-haque/ID-Service/src/utils/date"
"github.com/rezwanul-haque/ID-... |
package osbuild2
type MkfsBtrfsStageOptions struct {
UUID string `json:"uuid"`
Label string `json:"label,omitempty"`
}
func (MkfsBtrfsStageOptions) isStageOptions() {}
type MkfsBtrfsStageDevices struct {
Device Device `json:"device"`
}
func (MkfsBtrfsStageDevices) isStageDevices() {}
func NewMkfsBtrfsStage(opt... |
// Copyright 2020 Kuei-chun Chen. All rights reserved.
package mdb
import (
"errors"
"regexp"
"strconv"
"strings"
"github.com/simagix/gox"
)
var hasFilters = map[string]bool{"count": true, "delete": true, "find": true, "remove": true, "update": true, "aggregate": true, "getMore": true, "getmore": true, "findAn... |
// Copyright 2014 Chris Monson <shiblon@gmail.com>
//
// 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 arrays
import "fmt"
func findShortestSubArray(nums []int) int {
h := map[int]Degree{}
for i := 0; i < len(nums); i++ {
if d, ok := h[nums[i]]; ok {
d.value++
d.end = i
h[nums[i]] = d
} else {
h[nums[i]] = Degree{
value: 1,
start: i,
end: i,
}
}
}
maxDegree := 0
maxDegre... |
package discord
import (
"encoding/json"
"math"
"net/http"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"github.com/sasha-s/go-deadlock"
)
var lock = deadlock.RWMutex{}
func (b *Bot) exists(m *discordgo.MessageCreate, table string, where string, args ...interface{}) (bool, bool) {
res, err := b.db.Query... |
package template
func foo(_ interface{}) interface{} {
return nil
}
|
package spacesaving
import (
"container/heap"
"sort"
"github.com/dgryski/go-sip13"
)
// Element is a TopK item
type Element struct {
Key string
Count int
Error int
}
type elementsByCountDescending []Element
func (elts elementsByCountDescending) Len() int { return len(elts) }
func (elts elementsByCountDesce... |
package slacktest
import (
"log"
"net/http"
"net/http/httptest"
"sync"
slack "github.com/nlopes/slack"
)
type contextKey string
// ServerURLContextKey is the context key to store the server's url
var ServerURLContextKey contextKey = "__SERVER_URL__"
// ServerWSContextKey is the context key to store the server... |
package main
import (
"bufio"
"fmt"
"io"
"net"
"os"
"os/exec"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "3333"
CONN_TYPE = "tcp"
)
func main() {
l, err := net.Listen("tcp", "0.0.0.0:3333")
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
fmt.Println("Listening ...")
def... |
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/scrypt"
"io/ioutil"
"net/http"
"os"
"time"
)
// users are added at startup
var users = map[string][]byte{}
ty... |
// Partition Equal Subset Sum
// Dynamic Programming
//
// Time complexity: O(len(input) * targetSum)
// Space complexity: O(len(input) * targetSum)
//
// References:
// https://leetcode.com/problems/partition-equal-subset-sum/description/
// https://github.com/mission-peace/interview/blob/master/src/com/interview/dyna... |
package main
import (
"basic-rabbitmq/RabbitMQ"
"strconv"
"time"
)
func main() {
// Routing mode producer
workerOne := RabbitMQ.NewRabbitMQRouting("exGolang", "workerOne")
workerTwo := RabbitMQ.NewRabbitMQRouting("exGolang", "workerTwo")
for i := 0; i <= 50; i++ {
if i%3 == 0 {
workerOne.PublishRouting("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.