text stringlengths 11 4.05M |
|---|
package main
import "fmt"
func main() {
x := struct {
nome string
idade int
}{
nome: "Maior",
idade: 50,
}
fmt.Println(x)
}
|
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "swagger-filter",
Short: "Filter a swagger specification by endpoint",
Long: `Filter a swagger specification by endpoin... |
package confighandler
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestConfigHandler(t *testing.T) {
data := []byte(`
[streamjuryconfig]
SuperUserId = 123456
ChannelId = -987654
ApiKey = "abcdefg:1234"
ResultsAbsPath = "/var/www/blargh/"
`)
tomlConfig := LoadConfig(data)
assert.Equal(t, 123456... |
func main() {
conn, err := grpc.Dial("localhost:9999", grpc.WithInsecure())
if err != nil {
log.Fatalf("連線失敗:%v", err)
}
defer conn.Close()
c := pb.NewEchoClient(conn)
r, err := c.Echo(context.Background(), &pb.EchoRequest{Msg: "HI HI HI HI"})
if err != nil {
log.Fatalf("無法執行 Plus 函式:%v", err)
}
log.Prin... |
/*
Copyright © 2021 Faruk AK <kakuraf@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 or agreed to in wr... |
/*
命題
"paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
*/
package main
import (
"fmt"
"strings"
)
func biGram(str string) []string {
list := strings.Split(str, "")
var grams []string
for i := range list {
if i == 0 {
continue
... |
package main
func isMatch(s string, p string) bool {
isVisit = make(map[int]bool)
return isMatchExec(s, p, len(s), len(p))
}
var isVisit map[int]bool
func hash(ends, endp int) int {
return (ends << 20) | endp
}
func isMatchExec(s string, p string, ends, endp int) bool {
if ends == 0 && endp == 0 {
return true... |
package minion
import (
"testing"
"time"
"github.com/quilt/quilt/db"
"github.com/quilt/quilt/stitch"
"github.com/stretchr/testify/assert"
)
const testImage = "alpine"
func TestContainerTxn(t *testing.T) {
conn := db.New()
trigg := conn.Trigger(db.ContainerTable).C
spec := ""
testContainerTxn(t, conn, spec... |
package param
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/json-iterator/go"
"github.com/toolkits/pkg/errors"
)
func String(r *http.Request, key string, defVal string) string {
if val, ok := r.URL.Query()[key]; ok {
if val[0] == "" {
return defVal
}
return strings.TrimSpace... |
package logger
import (
"sync"
"github.com/sirupsen/logrus"
)
var logger *logrus.Logger
var onceInitLogger sync.Once
func Get() *logrus.Logger {
onceInitLogger.Do(func() {
logger = logrus.New()
logger.SetFormatter(&logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
"FieldKeyTime": "time",
"FieldKey... |
package gostomp
import (
"bytes"
"strings"
)
var (
replacerEncodeValues = strings.NewReplacer(
"\\", "\\\\",
"\r", "\\r",
"\n", "\\n",
":", "\\c",
)
replacerDecodeValues = strings.NewReplacer(
"\\r", "\r",
"\\n", "\n",
"\\c", ":",
"\\\\", "\\",
)
)
// Encodes a header value using STOMP value en... |
package structs
//easyjson:json
type User struct {
ID int
Name string
Login string
Password string
Email string
Status string
}
|
package backtracking
import "sort"
func permuteUnique(nums []int) [][]int {
sort.Ints(nums)
var res [][]int
var cur []int
help47(nums, map[int]bool{}, &res, &cur)
return res
}
func help47(nums []int, used map[int]bool, res *[][]int, cur *[]int) {
if len(*cur) == len(nums) {
tmp := make([]int, len(nums))
co... |
package reservasi
import(
"net/http"
"html/template"
"log"
"fmt"
conn "project_reservasi/src/config"
m "project_reservasi/src/model"
)
func ReservasiHandler(w http.ResponseWriter,r *http.Request){
http.FileServer(http.Dir("assets"))
// var data = map[string]interface{}{
// "title": "Learning Golang Web",
... |
func containsDuplicate(nums []int) bool {
m:=make(map[int]int)
for _,v:=range nums{
if _,ok:=m[v];ok{
return true
}
m[v] = 1
}
return false
}
|
package main
import (
"DeanFoleyDev/go-url-shortener/cmd/api"
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
readyCheck := make(chan struct{}, 1)
sigs := make(chan os.Signal, 1)
apiDone := make(chan struct{}, 1)
closedServices := make(chan struct{})
go api.Launch(readyCheck, apiDone, closedServices)
<-r... |
package main
import (
"bufio"
"errors"
"fmt"
"os"
homedir "github.com/mitchellh/go-homedir"
)
type FileInfo struct {
name string
namepath string
file *os.File
buf []string
}
func OpenFile(filename string) (*FileInfo, error) {
name, err := homedir.Expand(filename)
if err != nil {
return nil... |
package qstring
type MIMEType string
const (
Audio MIMEType = "application/vnd.google-apps.audio"
Document MIMEType = "application/vnd.google-apps.document"
Drawing MIMEType = "application/vnd.google-apps.drawing"
File MIMEType = "application/vnd.google-apps.file"
Folder MIMEType = ... |
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
func getBackupFile(prj Project) (string, error) {
// вариант, когда файл с бэкапом базы уже есть на диске
if len(prj.ExistFile) > 0 {
// извлекаем имя файла из полного пути
arr := strings.Split(prj.ExistFile, "/")
return arr[len(arr)... |
func fourSum(nums []int, target int) [][]int {
res := [][]int{}
sort.Ints(nums)
for idxa := 0; idxa < len(nums) - 3; idxa += 1{
va := nums[idxa]
if idxa > 0 && nums[idxa - 1] == va {
continue
}
for idxb := idxa + 1; idxb < len(nums) - 2; idxb += 1{
vb ... |
package fcache
import (
"testing"
)
// go test -run=^^$ -bench=^BenchmarkMemCacheSet$ -benchmem
func BenchmarkMemCacheSet(b *testing.B) {
cache := NewMemCache(100, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Set("key", []byte("value"))
}
}
// go test -run=^^$ -bench=^BenchmarkMemCacheGet$ -benchmem... |
//go:generate swagger generate spec
package main
import (
"fmt"
"net/http"
"os"
"github.com/getaceres/payment-demo/frontend"
"github.com/getaceres/payment-demo/persistence/mongo"
"github.com/gorilla/mux"
"github.com/spf13/cobra"
)
func main() {
var port int
var connectionURL string
var cmdServe = &cobra... |
package main
import (
"os"
"vm"
)
func main() {
vm := vm.NewVM()
vm.Execute(os.Args[1])
}
|
package datasetapi
import (
"context"
dstypes "github.com/lexis-project/lexis-backend-services-interface-datasets.git/client/data_set_management"
"github.com/lexis-project/lexis-backend-services-api.git/models"
"github.com/lexis-project/lexis-backend-services-api.git/restapi/operations/data_set_management"
"gith... |
package main
import (
"github.com/gorilla/mux"
"net/http"
"encoding/json"
"log"
)
type UserInfo struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/query/{name}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
//這邊就把 name... |
package canvas
import (
"fmt"
"strings"
"testing"
"github.com/calbim/ray-tracer/src/color"
)
func TestCanvas(t *testing.T) {
c := New(10, 20)
if c.width != 10 || c.height != 20 {
t.Errorf("Canvas width and height should be 10 and 20 respectively")
}
for i := 0; i < c.height; i++ {
for j := 0; j < c.width... |
package main
import (
l4g "base/log4go"
"net/http"
)
type HttpRequestInfo struct {
action string
req *http.Request
closeChan chan bool
}
func NewHttpRequestInfo(action string, req *http.Request, c chan bool) *HttpRequestInfo {
return &HttpRequestInfo{
action: action,
req: req,
closeChan... |
package marshall
import (
"fmt"
"testing"
)
func TestLoad(t *testing.T) {
var json_string string = `{
"basics": {
"name": "John Doe",
"label": "Programmer",
"image": "",
"email": "john@gmail.com",
"phone": "(912) 555-4321",
"url": "https://johndoe.com",
"summary": "A summary of John D... |
package models_test
import (
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"io"
"github.com/cloudfoundry-incubator/cloud-service-broker/db_service/models"
"github.com/cloudfoundry-incubator/cloud-service-broker/db_service/models/fakes"
"github.com/cloudfoundry-incubator/cloud-service-broker/internal/... |
package tesla
/// POST Get Access Token
// Auth is an authorization structure for the Tesla API.
var AuthURL = "/oauth/token"
type RefreshAuthToken struct {
GrantType string `json:"grant_type"`
RefreshToken string `json:"refresh_token"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
... |
package controllers
import (
"net/http"
"github.com/gorilla/mux"
"github.com/wbreza/go-store/api/models"
"github.com/wbreza/go-store/api/services"
)
// ProductController exposes actions on the products API
type ProductController struct {
Controller
productManager services.ProductManager
router mux.Rou... |
package prservice
import (
"net/http"
"io/ioutil"
"sync"
"time"
fm "github.com/cyg2009/MyTestCode/pkg/functionmanager"
)
func makeOKResponse(w http.ResponseWriter, body string){
//w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}
func makeFailedResponse(w... |
/*
Copyright [2015] Alex Davies-Moore
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 concurrent
type Func func()
type FuncMayError func() error
type FuncWithResult func() (result interface{})
type FuncWithResultMayError func() (result interface{}, err error)
|
// package main
//
// import (
// "fmt"
// "os"
// )
//
// func main() {
// // ファイルを開く
// file, err := os.Open("test.txt")
// // エラー判定
// if err != nil {
// // 失敗
// fmt.Println(err.Error())
// } else {
// // 成功
// fmt.Println("Successful!")
// file.Close()
// }
// }
// package main... |
package models
import (
"crypto/rand"
"encoding/base64"
"strings"
)
const numRandomBytes = 32
func GenerateRandomString() (string, error) {
b, err := GenerateRandomBytes(numRandomBytes)
if err != nil {
return "", err
}
return EncodeBase64WithoutPadding(b), nil
}
func GenerateRandomBytes(n int) ([]byte, er... |
package kvraft
import (
"crypto/rand"
"math/big"
"time"
"../labrpc"
"../raft"
)
var timeoutClientIntervals = []time.Duration{time.Duration(1 * time.Second), time.Duration(2 * time.Second), time.Duration(4 * time.Second)}
type Clerk struct {
servers []*labrpc.ClientEnd
// You will have to modify this struct.
... |
/*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the 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 ... |
/*
Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 ... |
package lambda
import (
"github.com/projecteru2/cli/cmd/utils"
"github.com/projecteru2/core/strategy"
"github.com/urfave/cli/v2"
)
// Command exports lambda subommands
func Command() *cli.Command {
return &cli.Command{
Name: "lambda",
Usage: "run commands in a workload like local",
Flags: []cli.Flag{
&... |
package client
import (
"github.com/maxence-charriere/go-app/v7/pkg/app"
)
// Menu ...
func Menu(home string) app.UI {
return app.Div().Body(
app.A().Href("/").Text(home),
app.A().Href("/foo").Text("Foo!"),
app.A().Href("/youtube").Text("Youtube!"),
app.A().Href("/spotify").Text("Spotify!"),
)
}
// MenuAs... |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-09-01 17:08
* Description:
*****************************************************************/
package pdlQrySvc
type TResData struct {
Status int ... |
package vastflow
import (
"errors"
"github.com/jack0liu/logs"
"github.com/satori/go.uuid"
"reflect"
"sync"
)
type errorBasin struct {
err error
}
type Headwaters struct {
// global context
RequestId string
ReqInfo interface{} // request info from andes
atlantic AtlanticStream
// basin context
basinMu... |
package commands
import (
// HOFSTADTER_START import
"fmt"
// HOFSTADTER_END import
"github.com/spf13/cobra"
)
// HOFSTADTER_START const
// HOFSTADTER_END const
// HOFSTADTER_START var
// HOFSTADTER_END var
// HOFSTADTER_START init
// HOFSTADTER_END init
var (
RootCmd = &cobra.Command{
Use: "hello... |
package main
import "fmt"
func main() {
var subject string = "Gopher"
fmt.Println("First element of Gopher string: ", string("Gopher"[0]))
fmt.Printf("The first value of the subject string: %v\n", string(subject[0]))
fmt.Printf("The last value of the subject string: %v\n", string(subject[len(subject)-1]))
fmt.... |
package middleware
import (
"os"
"github.com/gin-gonic/gin"
"github.com/zmb3/spotify"
)
var scopes = []string{
spotify.ScopeUserReadPrivate,
spotify.ScopePlaylistModifyPublic,
spotify.ScopePlaylistModifyPrivate,
}
//SpotifyRequired middleware func
func SpotifyRequired() gin.HandlerFunc {
redirectURI := os.Ge... |
package openid_test
import (
"fmt"
"net/http"
"github.com/emanoelxavier/openid2go/openid"
)
func AuthenticatedHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "The user was authenticated!")
}
func AuthenticatedHandlerWithUser(u *openid.User, w http.ResponseWriter, r *http.Request) {
fmt.Fprint... |
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/ONSdigital/aws-appsync-generator/pkg/graphql"
"github.com/pkg/errors"
flag "github.com/spf13/pflag"
)
var (
manifest = ""
)
func init() {
flag.StringVarP(&manifest, "manifest", "m", "manifest.yml", "manifest file to parse")
flag.StringVarP(&gr... |
package server
import (
"github.com/rs/zerolog"
)
type Handlers struct {
Healthcheck
}
func NewHandlers(log zerolog.Logger) *Handlers {
return &Handlers{
Healthcheck: NewHealthcheck(log),
}
}
|
package search
import (
"testing"
"github.com/takatori/mini-search/index"
"reflect"
)
func TestProxymityRanking(t *testing.T) {
collection := []string{
"Do you quarrel, sir?",
"Quarrel sir! no, sir!",
"If you do, sir, I am for you: I serve as good a man as you.",
"No better.",
"Well, sir",
}
writer... |
package backend
import (
"encoding/json"
"math/rand"
)
// User represents an active user. The user can be in a room, or in the placement queue.
// In this implementation we will NOT save user information into the database, as we allow
// register-less entrances. Therefore, we would like User to be as simple as poss... |
package main
import (
"os"
"github.com/followedwind/slackbot/internal/endpoint"
"github.com/followedwind/slackbot/internal/util"
"github.com/slack-go/slack"
"github.com/taketsuru-devel/gorilla-microservice-skeleton/serverwrap"
"github.com/taketsuru-devel/gorilla-microservice-skeleton/skeletonutil"
"github.com/... |
/*
for 循环
*/
package basicgrammar
/**
go已package为最小单位 定义的变量如果没有被引用idea是会报错的
这是一个for
func name的大写是 public的属性
*/
import (
"fmt"
)
//常量 const 访问权限也不一样 pkg都可以访问 使用
const b = "1213"
// break 中断整个循环 continue 中断当前循环 return 回调整个func
func Grammar() {
//变量 只能在函数 Grammar 使用
//变量命名规则 var 参数名称 类型 = 表达式
var s, sep string
//自... |
package _examples
import (
"reflect"
"testing"
"time"
"github.com/ompluscator/dynamic-struct"
"gopkg.in/go-playground/validator.v9"
)
func TestExample(t *testing.T) {
instances := []interface{}{
getReaderWithNewStructForJsonExample(),
getReaderWithExtendedStructForJsonExample(),
getReaderWithMergedStruct... |
package intmap
import "testing"
func TestMapInt32Set_Grow_OK(t *testing.T) {
m := NewMapInt32()
for i := int32(0); i < 100; i++ {
m.Set(i, i)
}
for i := int32(0); i < 100; i++ {
if m.Get(i) != i {
t.Fatalf("key: %d != %d", i, i)
}
}
}
func BenchmarkMapInt32Set_Stdlib(b *testing.B) {
// do bench
m :=... |
package util
import "regexp"
// Validator 数据格式验证
type Validator struct{}
// IsMobile 判断是否为手机号
func (Validator) IsMobile(value string) bool {
result, _ := regexp.MatchString(`^(1[0-9][0-9]\d{4,8})$`, value)
return result
}
// IsPhone 判断是否为固定电话号码
func (Validator) IsPhone(value string) bool {
result, _ := regexp.Ma... |
package blob
import (
"encoding/json"
"golang.org/x/net/context"
"google.golang.org/appengine/log"
"google.golang.org/appengine/memcache"
"github.com/firefirestyle/engine-v01/prop"
)
type BlobManager struct {
config BlobManagerConfig
}
type BlobManagerConfig struct {
Kind string
PointerKind string
... |
package runner
import (
"context"
"fmt"
"strings"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/rs/zerolog/log"
)
// Call executes an request on url using the runner context.
// ctx must be a valid runner context created with WithContext method of a runner instance.
/... |
package models
import (
"GridService/Service-Spacdt/models/spacbasic"
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/pkg/errors"
"xh.common/xh_util"
_ "github.com/astaxie/beego"
"github.com/streadway/amqp"
)
func init() {
spacbasic.NativeInit()
}
var (
rabbit... |
package handler
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"proxy_download/common"
"proxy_download/model"
"strconv"
"strings"
)
func VariableDetail(context *gin.Context) {
var variable model.Variable
idString := context.Param("id")
id, _ := strconv.ParseInt(idString, 10, 64)
variableDeta... |
package wikipedia
import "net/http"
import "net/url"
import "errors"
import "fmt"
import "encoding/json"
import "strings"
const LANGUAGE_URL_MARKER = "{language}"
type Wikipedia interface {
Page(title string) Page
PageFromId(id string) Page
GetBaseUrl() string
SetBaseUrl(baseUrl string)
SetImagesResults(imagesR... |
package rstreams
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/tunnel"
"github.com/batchcorp/plumber/validate"
)
func (r *Redis... |
package view
import (
"html/template"
"io"
"net/http"
)
var (
VIEW_PREFIX = "view/"
VIEW_SUFFIX = ".html"
)
type ViewResolver struct {
View *View
Writer io.Writer
}
func (v *ViewResolver) Resolve() {
handlerView := *v.View
layoutName := handlerView.GetLayout()
viewName := handlerView.GetView()
var view... |
package workspace
import (
"archive/zip"
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
"testing"
"github.com/databrickslabs/databricks-terraform/common"
"github.com/databrickslabs/databricks-terraform/internal/qa"
"github.... |
package app
import (
"github.com/hashicorp/golang-lru/simplelru"
pTest "github.com/skos-ninja/truelayer-tech/svc/pokemon/services/pokeapi/test"
sTest "github.com/skos-ninja/truelayer-tech/svc/pokemon/services/shakespeare/test"
)
func newTestApp(pokemon, translation bool) *app {
pokeAPI := pTest.New(pokemon)
pLRU... |
// Unit tests for file configuration repository.
//
// @author TSS
package file
import (
"testing"
"github.com/mashmb/1pass/1pass-core/core/domain"
)
func setupFileConfigRepo() (*fileConfigRepo, *fileConfigRepo) {
return NewFileConfigRepo("../../../assets"), NewFileConfigRepo("")
}
func TestIsAvailable(t *testi... |
//
// Copyright (c) 2017 Intel Corporation
//
// 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... |
package consumers
import (
"testing"
)
func TestShouldSkipRecord(t *testing.T) {
var tests = []struct {
offset int64
skip int64
parseKey bool
key []byte
expected bool
err bool
}{
// no keys
{offset: 0, skip: 0, parseKey: false, key: make([]byte, 0), expected: false},
{offset: 1, ... |
// Copyright 2021 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 reduce(s string) (r string) {
for i := 0; i < len(s); i++ {
if i < len(s)-1 && s[i] == s[i+1] {
i++
} else {
r += string(s[i])
}
}
return r
}
func isUpper(c byte) bool {
return c >= 'A' && c <= 'Z'
}
func countCamelCaseWords(s string) int {
if len(s) == 0 {
return 0... |
package v1alpha1
import (
dbmodels "github.com/xinsnake/databricks-sdk-golang/azure/models"
)
// ClusterSpec is similar to dbmodels.ClusterSpec, the reason it
// exists is because dbmodels.ClusterSpec doesn't support ExistingClusterName
// ExistingClusterName allows discovering databricks clusters by it's kubernetes... |
package main
import (
pb "example/communication"
"fmt"
"log"
"net"
myerr "example/error"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
// Define localhost address infomation
const (
address = "127.0.0.1"
defaultname = "server"
port = 6666
)
// set i... |
package auth
import (
"fmt"
sdk "github.com/irisnet/irishub/types"
)
// GenesisState - all auth state that must be provided at genesis
type GenesisState struct {
CollectedFees sdk.Coins `json:"collected_fee"`
FeeAuth FeeAuth `json:"data"`
Params Params `json:"params"`
}
// Create a new genesis... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"testing"
"time"
"github.com/giuseppe7/diane/internal"
)
func TestInitObservability(t *testing.T) {
initObservability()
tr := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 10 * time.Second,
}
httpClient := &http.Client{
Transport... |
// A Tour of Go : Flow control statements: for, if, else, switch and defer
// https://to-tour-jp.appspot.com.list/flowcontrol/1
package main
import (
"fmt"
"math"
"runtime"
"time"
)
func main() {
{
// for ループ
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println("1-1. ", sum)
// 初期化と後処理ステートメ... |
package handlers
import (
"github.com/gorilla/context"
"github.com/roger-king/go-ecommerce/pkg/models"
"github.com/roger-king/go-ecommerce/pkg/utilities"
"github.com/sirupsen/logrus"
"net/http"
)
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Re... |
package mockery
import "github.com/mitooos/thesis/mockery/model"
type UserRepository interface {
InsertUser(*model.User) error
}
type SecurityHelper interface {
HashPassword(string) (string, error)
}
type service struct {
repository UserRepository
securtiyHelper SecurityHelper
}
func (s *service) InsertUse... |
package generated
type Object struct {
tableName struct{} `sql:"foo"`
ID string `json:"id" sql:"type:uuid,default:gen_random_uuid()"`
CreatedBy string `json:"createdBy"`
CreatedAt string `json:"createdAt" sql:"default:now()"`
Foo bool `json:"foo"`
Bar float64 `json:"bar"`
Baz ... |
package queue
import (
"encoding/json"
"errors"
"math"
"time"
"github.com/spf13/viper"
"github.com/steam-authority/steam-authority/logging"
"github.com/streadway/amqp"
)
const (
QueueApps = "Steam_Apps"
QueueAppsData = "Steam_Apps_Data"
QueueChangesData = "Steam_Changes_Data"
QueueDelaysData ... |
package kindergarten
import (
"errors"
"sort"
"strings"
)
type Garden map[string][]string
var plants = map[rune]string{
'R': "radishes",
'C': "clover",
'G': "grass",
'V': "violets",
}
func NewGarden(diagram string, children []string) (*Garden, error) {
g := Garden{}
if diagram[0] != '\n' {
return nil, er... |
package balloc
import (
"errors"
"fmt"
"runtime"
"sync"
"sync/atomic"
"unsafe"
)
var (
ErrOutOfMemory = errors.New("Not enough space allocating memory")
ErrInvalidSize = errors.New("The requested size is invalid")
)
const maxBufferSize = 0x8000000000
const alignmentBytes = 8
const alignmentBytesMinusOne = al... |
package main
import (
"fmt"
"github.com/valyala/fasthttp"
)
func main(){
fasthttp.ListenAndServe(":8080",requestHandler)
}
func requestHandler(ctx *fasthttp.RequestCtx){
fmt.Fprintf(ctx,"m:%q,user:%q\n",ctx.Method(),ctx.UserAgent())
}
|
package util
const (
VERSION = "0.72"
)
|
package modeltests
import (
"github.com/victorsteven/fullstack/api/models"
"log"
"testing"
_ "github.com/jinzhu/gorm/dialects/mysql"
"gopkg.in/go-playground/assert.v1"
)
func TestFindAllPosts(t *testing.T) {
err := refreshUserAndPostTable()
if err != nil {
log.Fatalf("Error refreshing user and post table %... |
package main
import (
"fmt"
"github.com/ParsePlatform/go.inject"
"os"
)
// Interfaces
type CARFACTORY interface {
makeCar() CAR
getMake() string
}
type CAR interface {
getModel() string
}
// Concrete implementations
type FordFactory struct {
car *FordMondeo `inject:""`
}
type FordMondeo struct {
}
func (... |
package main
import (
"fmt"
"io/ioutil"
)
func main() {
dir := "testdata"
fis, err := ioutil.ReadDir(dir)
if err != nil {
panic(err)
}
for _, fi := range fis {
fmt.Printf("%#v\n", fi)
fmt.Printf("fi.Name():%q\n\n", fi.Name())
}
}
|
package main
import (
"flag"
"log"
"net/http"
"strconv"
"sync"
"github.com/mindprince/gonvml"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
namespace = "nvidia_gpu"
)
var (
addr = flag.String("web.listen-address", ":9445", "Address to ... |
package models
import (
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var DB *gorm.DB
func InitDB(dbstring string) {
if dbstring == "$dbstring" {
dbstring = os.Getenv("dbstring")
}
var err error
DB, err = gorm.Open("postgres", dbstring)
if err != nil {
panic(err)
}
}
f... |
// Generated by ego on Sun Jun 14 13:23:31 2015.
// DO NOT EDIT
package main
import (
"fmt"
"html"
"io"
"github.com/kyokomi/slackbot/plugins"
)
//line templates/index.html.ego:1
func IndexTmpl(w io.Writer, pList []plugins.Plugin) error {
//line templates/index.html.ego:2
_, _ = fmt.Fprint(w, "\n\n")
//line templates... |
package main
import (
"time"
)
type ChannelImage struct {
Url string
}
type ChannelMovie struct {
Url string
}
type ChannelItem struct {
Id int
ChannelId int
Title string
Url string
PublishedAt *time.Time
TweetedAt *time.Time
Images []*ChannelImage
Movies []*ChannelMovie
}
type Channel struct {
Id int
... |
package rigis
import (
"net/http"
"net/http/httputil"
"net/url"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
type backendHost struct {
weight int
url *url.URL
rp *httputil.ReverseProxy
}
func newBackendHost(weight int, beURL *url.URL) backendHost {
bh := backendHost{
weight: weight,
... |
package storage
import (
"context"
"sync"
pb "github.com/vic3r/Microservice-Go/shippy/shippy-service-consignment/proto/consignment"
r "github.com/vic3r/Microservice-Go/shippy/shippy-service-consignment/repository"
)
type Storage struct {
mu sync.RWMutex
consignments []*pb.Consignment
}
var _ r.Repos... |
package handlers
import (
"errors"
"fmt"
"github.com/RecleverLogger/customerrs"
"github.com/RecleverLogger/logger"
"github.com/RecleverLogger/logger/repository"
"net/http"
)
type Config struct {
DbUrl string
DbInitialMigratePath string
}
type Service struct {
Handlers Handlers
db repos... |
// Copyright 2018 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
// ===========================================================================
// IsLess returns a Predicate
// which is useful to disriminate... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
// Copyright (c) 2020 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package util
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// ReadArgsFile parses the args file and populates the map with the contents
// of that file. The pars... |
package color
const (
IndianRed = "#CD5C5C"
LightCoral = "#F08080"
Salmon = "#FA8072"
DarkSalmon = "#E9967A"
LightSalmon = "#FFA07A"
Crimson = "#DC143C"
Red = "#FF0000"
FireBrick = "#B22222"
DarkRed = "#8B0000"
Cornsilk = "#FFF8DC"
BlanchedAlmond = "#FFEBCD"
Bisque ... |
package core
import (
"errors"
)
// OrderTransactionType describes the transaction type: Bid / Ask
type OrderTransactionType uint
const (
// Bid - we are buying the base of a currency pair, or selling the quote
Bid OrderTransactionType = iota
// Ask - we are selling the base of a currency pair, or buying the quo... |
package manager
import (
"errors"
"strings"
)
func GetVideoIDFromLink(link string) (string, error) {
var err = errors.New("Invalid link!")
parts := strings.Split(link, "=")
if len(parts) != 2 {
return "", err
}
return parts[1], nil
}
func IsLinkFromYoutube(link string) bool {
if strings.HasPre... |
package arangoapi
import "gopkg.in/kataras/iris.v6"
import "time"
import "strconv"
type TimeElapsed struct {
Startime int64 `json:"startime"`
Endtime int64 `json:"endtime"`
Duration int64 `json:"duration"`
}
func Read(ctx *iris.Context) {
var timer TimeElapsed
timer.Startime =time.Now().UnixNano()
Create... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.