text stringlengths 11 4.05M |
|---|
package router
import (
"fmt"
"net/http"
"strings"
"github.com/pkg/errors"
"github.com/shharn/blog/logger"
)
var (
mapStatusCodeToMessage = map[int]string{
http.StatusBadRequest: "Bad Request",
http.StatusUnauthorized: "Invalid authentication data",
http.StatusForbidden: "Not allowed to do it",
http.St... |
package main
import (
"testing"
)
func TestScore(t *testing.T) {
var absTests = []struct {
candidate Candidate
query string
wanted float32
}{
{candidate: NewCandidate("a"), query: "", wanted: 1.0},
{candidate: NewCandidate("a"), query: "aa", wanted: 0.0},
{candidate: NewCandidate("abcx"), query... |
//Copyright (c) 2017 Phil
//Package apollo ctrip apollo go client
package apollo
var (
defaultClient *Client
)
// Start apollo
func Start() error {
return StartWithConfFile(defaultConfName)
}
// StartWithConfFile run apollo with conf file
func StartWithConfFile(name string) error {
log.Debugf("StartWithConfFile ... |
package middleware
import (
"github.com/best-expendables/httpclient/net/profile"
"net/http"
log "github.com/best-expendables/logger"
)
// ResponseLogger create log for response
type ResponseLogger struct {
logger
}
// NewResponseLogger create logger for response
func NewResponseLogger(loggerEntry log.Entry) *Re... |
package fuse_test
import (
"os"
"testing"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse"
)
func TestOpenFlagsAccmodeMaskReadWrite(t *testing.T) {
var f = fuse.OpenFlags(os.O_RDWR | os.O_SYNC)
if g, e := f&fuse.OpenAccessModeMask, fuse.OpenReadWrite; g != e {
t.Fatalf("OpenAccessModeMask behaves... |
package model
import (
"bytes"
"fmt"
"time"
"tpay_backend/utils"
"gorm.io/gorm"
)
const TransferOrderTableName = "transfer_order"
const (
// 代付订单状态
TransferOrderStatusPending = 1 // 待支付
TransferOrderStatusPaid = 2 // 已支付
TransferOrderStatusFail = 3 // 支付失败
// 代付订单异步通知状态
TransferNotifyStatusNot ... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-10 08:19
# @File : lt_61_Rotate_List.go
# @Description :
# @Attention :
*/
package v0
/*
旋转链表
将其构建成环
找到新的头结点: 新的头节点在 n-(k%n) 处
新的尾节点: 在 n-(k%n)-1 处
*/
func rotateRight(head *ListNode, k int) *ListNode {
if nil == head {
return nil
}
walkerNode... |
package main
import (
"fmt"
"log"
"os"
"github.com/knusbaum/go9p/fs"
"github.com/knusbaum/go9p/server"
)
var readme string = `# To look up a word, open and read a file with the
# word's name under /words. For example, to read the definition
# of the word 'tree', read the file /words/tree. If the file
# doesn't ... |
package user
type insertRequest struct {
ExternalId string `json:"externalId" validate:"required"`
}
func insertRequestConvert(r *insertRequest) *User {
return &User{
ExternalId: r.ExternalId,
}
}
type insertResponse User
func newInsertResponse(group *User) *insertResponse {
return (*insertResponse)(group)
}
... |
package util
import (
"encoding/json"
"fmt"
"strings"
)
// SmartPrint formats messages as text or JSON with a given severity.
func SmartPrint(severity, m string, jsonOut bool) {
if jsonOut {
if severity == "" {
fmt.Printf(m)
return
}
outMap := make(map[string]string)
outMap[severity] = m
b, _ :=... |
/**
* 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 main
import (
"fmt"
"github.com/robertkrimen/otto"
)
func main() {
vm := otto.New()
vm.Run(`
abc = 2 + 2;
console.log("The value of abc is " + abc); // 4
`)
// get a value from vm
if value, err := vm.Get("abc"); err == nil {
if value_int, err := value.ToInteger(); err == ni... |
package fmm
import (
"bytes"
"encoding/binary"
"io"
)
type DatReader struct {
reader *bytes.Reader
}
func newDatReader(source []byte) DatReader {
return DatReader{
reader: bytes.NewReader(source),
}
}
func (d *DatReader) Advance(offset int64) {
d.reader.Seek(offset, io.SeekCurrent)
}
func (d *DatReader) R... |
package test
import (
"context"
"fmt"
"testing"
ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
pt "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer/test"
)
func multiaddr(m string) ma.Mul... |
package server
import "github.com/RecleverLogger/server/handlers"
type Config struct {
Port string
ReadTimeout int
WriteTimeout int
IdleTimeout int
UseTls bool
TLSCertFile string
TLSKeyFile string
Handlers handlers.Handlers
} |
/**
*@Author: haoxiongxiao
*@Date: 2019/1/26
*@Description: CREATE GO FILE api_services
*/
package hotel_api_services
const (
appId = 58443
appSecret = "3bd66623713248bab7c97eabe481bbcd"
)
type CommonRequestParams struct {
ShowapiAppid string `json:"showapi_appid"` //100
ShowapiSign string `json... |
package nlu
import (
"github.com/oshankkumar/GatewayOmega/client"
ghttp "github.com/oshankkumar/GatewayOmega/http"
"github.com/oshankkumar/GatewayOmega/services"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"net/http"
)
type Nlu struct{}
func newNLUService(opts ...services.SerivceOptionFunc) services.... |
package main
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/go-martini/martini"
"github.com/yosssi/rendergold"
"net/http"
"net/http/httptest"
"testing"
)
var (
response *httptest.ResponseRecorder
)
func Request(method string, route string, handler martini.Handler)... |
package podstore
import (
"time"
podstore_protos "github.com/square/p2/pkg/grpc/podstore/protos"
"github.com/square/p2/pkg/launch"
"github.com/square/p2/pkg/manifest"
"github.com/square/p2/pkg/store/consul"
"github.com/square/p2/pkg/store/consul/consulutil"
"github.com/square/p2/pkg/store/consul/podstore"
"gi... |
/*
In 2014, demoscener Jakub 'Ilmenit' Debski released a 250-byte(1) procedural graphics demo for the Atari XL called Mona. It's drawing the following picture(2):
mona
Your task is to generate the exact same picture, using the language of your choice.
(1) Breakdown: 136 bytes of data + 114 bytes of code.
(2) The or... |
package apptweak
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type AppDetailResponse struct {
AD AppDetail `json:"content"`
MD MetaData `json:"metadata"`
}
type ErrorResponse struct {
Err string `json:"error"`
ApplicationID int `json:"application_id,omitempty"`
Device string `j... |
package sstable
import (
"io"
"sort"
)
type ReadAtCloser interface {
io.ReaderAt
io.Closer
}
type SSTable struct {
f ReadAtCloser
r []record
m []byte
}
type record struct {
key string
length uint32
offset uint32
cksum uint32
}
func New(f ReadAtCloser) (*SSTable, error) {
t := &SSTable{f, nil, nil}
... |
package imagekit
//
// RESPONSES
//
type MetadataResponse struct {
Density int `json:"density"`
EXIF *MetadataResponseEXIF `json:"exif"`
Format string `json:"format"`
HasColorProfile bool `json:"hasColorProfile"`
HasTransparency bool ... |
package sshd
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/yankeguo/bastion/sshd/sandbox"
"github.com/yankeguo/bastion/types"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc"
"net"
)
type SSHD struct {
opts types.SSHDOptions
listener net.Listen... |
package main
import (
"log"
"testing"
nats "github.com/nats-io/nats.go"
"github.com/satori/uuid"
)
type SalesItem struct {
ItemID string `json:"ID"`
Name string `json:"name"`
Qty float32 `json:"qty"`
UnitPrice float32 `json:"unitprice"`
Status string `json:"status"`
Location string `j... |
package document
import (
"fmt"
)
// ErrDocNotFound returned if desired document not found
type ErrDocNotFound struct {
Annotation string
Kind string
}
func (e ErrDocNotFound) Error() string {
return fmt.Sprintf("Document annotated by %s with Kind %s not found", e.Annotation, e.Kind)
}
|
//
// Copyright 2020 The AVFS 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 ag... |
package lib
const (
// PROD 正式环境
PROD = "prod"
// DEV 开发环境,一般用于本机测试
DEV = "dev"
// TEST 测试环境
TEST = "test"
)
// Resp 用于定义返回数据格式(json)
type Resp struct {
Ret Code `json:"ret"`
Msg string `json:"msg,omitempty"`
Detail string `json:"detail,omitempty"`
Data interface{} `json:"data,omite... |
package main
/*
Create basic nodejs generator.
Requirements:
Write to package.json (use npm install or perhaps
use base template and allow user to fill in options)
*/
func main() {
t := generator{map[string]bool{
"package.json": true,
"app.js": true,
"index.html": true,
"js": true,
"css": true,
}... |
// Copyright 2015 The Chromium 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 common implements code and utilities shared across all packages in
// client/.
package common
|
package cmd
import (
"fmt"
"strconv"
"strings"
"github.com/Unreal4tress/go-sourceformat/vmf"
"gonum.org/v1/gonum/spatial/r3"
)
type DispInfo struct {
Power int
Seps int
StartPosition r3.Vec
Normals [][]r3.Vec
Distances [][]float64
}
func parseDispInfo(side *vmf.Node) *DispInfo {... |
package route
type insertRequest struct {
Route string `json:"route" validate:"required"`
Description string `json:"description" validate:"required"`
Method string `json:"method" validate:"required"`
Tags []string `json:"tags"`
}
type updateRequest struct {
Route string `json:"rou... |
package iface
import (
"log"
"time"
)
type WeatherCode int
const (
CodeUnknown WeatherCode = iota
CodeCloudy
CodeFog
CodeHeavyRain
CodeHeavyShowers
CodeHeavySnow
CodeHeavySnowShowers
CodeLightRain
CodeLightShowers
CodeLightSleet
CodeLightSleetShowers
CodeLightSnow
CodeLightSnowShowers
CodePartlyCloud... |
package main
import (
"fmt"
"./connection"
"./control"
_ "github.com/lib/pq"
)
func main() {
db := connection.Connection()
fmt.Print("\n\n[1] C\n[2] R\n[3] U\n[4] D\n->")
option := 0
fmt.Scanf("%d", &option)
switch option {
case 1:
control.Create(db)
db.Close()
break
case 2:
control.Read(db)
... |
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan string)
cs := make(chan string)
go func() {
for {
c <- "Every 100ms"
time.Sleep(time.Millisecond * 100)
}
}()
go func() {
for {
cs <- "Every second"
time.Sleep(time.Second * 1)
}
}()
for {
select {
case r := <-c:
... |
package gorpc
import (
"bufio"
"compress/flate"
"encoding/gob"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
// Rpc client.
//
// The client must be started with Client.Start() before use.
//
// It is absolutely safe and encouraged using a single client across arbitrary
// number of concurrently running gor... |
package equinix
import (
"context"
"fmt"
"log"
"time"
"github.com/equinix/ecx-go/v2"
"github.com/equinix/rest-go"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2... |
package watcher
import (
"fmt"
"fs_sync/files"
"fs_sync/models"
"fs_sync/modules/cmd"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
)
var userHost = models.UserHost{
User: "vagrant",
Host: "192.168.10.101",
}
type Watcher struct {
FileSyncManager *files.FileSyncManager
... |
// Copyright 2013 Google Inc. All rights reserved.
// Copyright 2016 the gousb Authors. 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.... |
// Copyright (c) 2014 James Wendel. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package auth
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"sync"
"time"
)
type datastore struct {
mutex sync.RWMutex
authFilename string... |
package main
import (
"sync"
"sync/atomic"
"fmt"
)
func main() {
var sum uint32 = 100
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
//sum += 1 //1
atomic.AddUint32(&sum, 1) //2
fmt.Println(sum)
}()
}
wg.Wait()
fmt.Println(sum)
}
|
package ex122
import (
"os"
"reflect"
"testing"
)
// This test ensures that the program terminates without crashing.
func Test(t *testing.T) {
// Even metarecursion! (YMMV)
Display("rV", reflect.ValueOf(os.Stderr))
// Output:
// Display rV (reflect.Value):
// (*rV.typ).size = 8
// (*rV.typ).ptrdata = 8
// ... |
package gopd
import (
"bytes"
"encoding/json"
"fmt"
)
const DOCUMENT_API_ENDPOINT = "https://api.pandadoc.com/public/v1/documents"
type FromTemplateDocument struct {
Name string `json:"name"`
TemplateUuid string `json:"template_uuid"`
Recipients []Recipient `json:"recipients"`
Tokens []Tok... |
package consumer
import (
"context"
rabbitmqmodels "github.com/superbet-group/code-cadets-2021/lecture_3/03_project/calculator/internal/infrastructure/rabbitmq/models"
)
// Consumer offers methods for consuming from input queues.
type Consumer struct {
betFromControllerConsumer BetFromController
eventUpdateCon... |
package iproto
// Абстрагируемся от способа серилизации и десерилизации сущности
type Marshaller interface {
Marshal() ([]byte, error)
UnMarshal([]byte) error
}
func Marshal(val Marshaller) ([]byte, error) {
data, err := val.Marshal()
if err != nil {
return nil, err
}
return data, nil
}
func UnMarshal(src []... |
package machines
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
configv1 "github.co... |
package mux
import (
"reflect"
"testing"
)
func TestExtractPathVars(t *testing.T) {
type args struct {
pattern string
}
tests := []struct {
name string
args args
wantPath string
wantVars []pathVar
wantErr bool
}{
{"noVars", args{"/path/to/resource"}, "/path/to/resource", []pathVar{}, fal... |
package agent
import (
"sync"
"time"
"github.com/bryanl/dolb/kvs"
etcdclient "github.com/coreos/etcd/client"
"golang.org/x/net/context"
)
// Locker locks and blocks until it is unlocked.
type Locker interface {
Lock() error
Unlock() error
}
type etcdLocker struct {
context context.Context
key string
w... |
package main
// TODO: we shouldn't need to prefix Go command with path, it should honor the PATH when sshing in
// there may be an issue with the ssh library, or possibly just something misconfigured with the pi we're testing on
import (
"encoding/json"
"fmt"
"github.com/ClarityServices/skynet2"
"github.com/Clari... |
package std
import (
_ "fmt"
"github.com/iansmith/tropical"
)
type DefaultMouseDispatch struct {
focusPolicy tropical.MousePolicy
focusedInteractor tropical.Interactor
FocusPolicies []tropical.MousePolicy
Monitors []tropical.MouseMonitor
}
func NewDefaultMouseDispatch() tropical.MouseDispatch {
r... |
package cmd
import (
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/mitchellh/colorstring"
"github.com/nwlucas/proj-cli/env"
"github.com/spf13/cobra"
)
var cmdDebug = &cobra.Command{
Use: "debug",
Short: "Spews out debug info.",
Long: `This is to be used for debug purposes.
... |
package relay
import (
"context"
"fmt"
"time"
"github.com/pkg/errors"
"google.golang.org/grpc"
"github.com/batchcorp/collector-schemas/build/go/protos/records"
"github.com/batchcorp/collector-schemas/build/go/protos/services"
"github.com/batchcorp/plumber/backends/rstreams/types"
)
var (
ErrMissingID ... |
package module
import (
"fmt"
"roman/database"
rn "roman/proto/roman"
"strings"
roman "github.com/StefanSchroeder/Golang-Roman"
)
type QuestionUnit struct {
model *database.Model
listUnitNumber []database.UnitNumber
}
func (qu *QuestionUnit) generateListUnit(stringResult string, tokenAnalysis *rn.To... |
package mat
type Shape interface {
ID() int64
GetTransform() Mat4x4
GetInverse() Mat4x4
GetInverseTranspose() Mat4x4
SetTransform(transform Mat4x4)
GetMaterial() Material
SetMaterial(material Material)
IntersectLocal(ray Ray) []Intersection
NormalAtLocal(point Tuple4, intersection *Intersection) Tuple4
GetLo... |
package auth
import (
"chlorine/cl"
"chlorine/storage"
"github.com/gorilla/sessions"
"log"
)
func GetMemberIfAuthorized(service cl.MemberService,
session *sessions.Session) (*storage.Member, bool) {
memberID, ok := session.Values["MemberID"].(int)
if !ok {
return nil, false
}
member, err := service.GetMemb... |
package testdata
import (
"github.com/frk/gosql/internal/testdata/common"
)
type SelectWithRecordNestedSliceQuery struct {
Nesteds []*common.Nested `rel:"test_nested:n"`
}
|
package main
type Settings struct {
BotToken,
YouTubeDeveloperKey,
MusicGraphKey,
GuildID,
TextChannelID,
VoiceChannelID string
}
type Genre struct {
ID, Name string
}
type Song struct {
ID, QueueID, Title, OrderedBy, Duration, Status, VideoURL string
VK ... |
package bson
import (
"reflect"
"github.com/EverythingMe/bson/bson"
"github.com/dvirsky/go-pylog/logging"
"github.com/EverythingMe/meduza/query"
"github.com/EverythingMe/meduza/transport"
)
type BsonProtocol struct {
}
func read(msg transport.Message, v interface{}) error {
if err := bson.Unmarshal(msg.Body, ... |
// 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 postgres_backend
import (
"database/sql"
"encoding/json"
"errors"
"github.com/howbazaar/loggo"
"github.com/lib/pq"
"github.com/straumur/straumur"
"time"
)
var (
logger = loggo.GetLogger("straumur.postgres")
)
// Callback for a managed transaction
//
// Example:
//
// err := p.wrapTransaction(func(tx ... |
// 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... |
package bslib
var faCachedValues = map[string]string{
"fab fa-500px": "",
"fab fa-accessible-icon": "",
"fab fa-accusoft": "",
"fas fa-address-book": "",
"fas fa-address-card": "",
"fas fa-a... |
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package utils
import (
"context"
"crypto/tls"
"os"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
backuppb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/log"
berrors "github.com/pingcap/tidb/br/pkg/errors"
"gi... |
package git
import (
"strings"
"testing"
)
func TestPatch(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
_, originalTreeId := seedTestRepo(t, repo)
originalTree, err := repo.LookupTree(originalTreeId)
checkFatal(t, err)
_, newTreeId := updateReadme(t, repo, "file cha... |
package pythagorean
type Triplet [3]int
func Range(min, max int) []Triplet {
slice := []Triplet{}
for a := min; a <= max; a++ {
for b := a; b <= max; b++ {
sumOfSquares := a * a + b * b
root := squareRoot(sumOfSquares)
if min <= root && root <= max && root * root == sumOfSquares {
slice = append(slic... |
package MonitorInfo
type InterfacesInfo struct {
BandwidthMaps map[string]BandwidthInfo `json:"bandwidthMaps"`
RemoteIpMaps map[string]string `json:"remoteIpMaps,omitempty"`
}
type BandwidthInfo struct {
Rx float64 `json:"rx"`
Tx float64 `json:"tx"`
}
type ConnectionInfo struct {
PacketLoss float64 `json... |
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"io/ioutil"
"math/big"
"strings"
"time"
)
var (
extKeyUsage = flag.String("extKeyUsage", "server", "server or client")
)
func run(name string) error {
key, err := rsa.GenerateKey(rand.Reader, ... |
package handlers
import (
"encoding/json"
"github.com/roger-king/go-ecommerce/pkg/models"
"github.com/roger-king/go-ecommerce/pkg/utilities"
"net/http"
)
func FindProductsController(w http.ResponseWriter, req *http.Request) {
products, err := models.AllProducts()
if err != nil {
utilities.RespondWithError(w,... |
package stuff
import (
"fmt"
"log"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
)
var _ Scraper = PhoneScoopScraper
var PhoneScoopScraper = func() []Vitalstats {
allDevices := make([]Vitalstats, 0, 2500)
doc, err := goquery.NewDocument("http://www.phonescoop.com/phones/index_all.php")
if err != nil {
... |
package statsd
import (
"testing"
"github.com/atlassian/gostatsd"
"github.com/atlassian/gostatsd/pb"
"github.com/stretchr/testify/require"
)
func TestHttpForwarderV2Translation(t *testing.T) {
t.Parallel()
metrics := []*gostatsd.Metric{
{
Name: "TestHttpForwarderTranslation.gauge",
Value: 12345... |
// Copyright (c) 2020 twihike. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.
package structconv
import (
"errors"
"reflect"
"strings"
)
var (
requiredTagValue = "required"
convTagValue = "conv"
)
type fieldInfo struct {
Meta r... |
package routers
import (
"quickstart/controllers"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/api/list", &controllers.TestController{}, "*:List")
beego.Router("/person/:last/:first", &controllers.TestController{})... |
package main
import (
"fmt"
"time"
)
type Stopwatch struct {
start, stop time.Time // no need for lap, see mark
mark time.Duration // mark is the duration from the start that the most recent lap was started
laps []time.Duration //
}
// New creates a new stopwatch with starting time offset ... |
package repositories
import (
"io"
"log"
)
func closeConnection(conn io.Closer) {
if err := conn.Close(); err != nil {
// Do we want to crash the application in this case?
log.Fatalln(err)
}
} |
package main
import (
"encoding/xml"
"io"
"strconv"
"strings"
"time"
"fmt"
)
type Message struct {
Id string
Type string
Timestamp time.Time
Notify []string
}
func main() {
x := `<message from="01234567890@s.whatsapp.net"
id="1339831077-7"
type="chat"
timestamp="1... |
package main
import (
"fmt"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/labstack/echo/engine/standard"
"github.com/marmelab/snake-solver-server/lib"
)
func main() {
type Data struct {
Width int `json:"width"`
Height int `json:"hei... |
package main
import (
bt "../structs/btree"
que "../structs/queue"
"fmt"
)
//打印二叉树节点数据
func PrintTreeLayer(root *bt.BTree, queue *que.SliceQueue) int {
var maxSum, preMaxSum int
if root != nil {
queue.Push(root)
}
for !queue.IsEmpty() {
var ldata, rdata int
childNode := queue.Pop().(*bt.BTree)
fmt.Pr... |
package database
import (
"log"
"testing"
)
func Test_db(t *testing.T) {
dbSvc := new(DataBaseSvc)
dbSvc.SetConnectionString("driver={SQL Server};server=xa-lsr-jimweiw7\\sqlserver14;database=ACCOUNT_000001_KAIKEI;user id=sa;pwd=xA123456;")
db := dbSvc.CreateDb()
var count int
row := db.QueryRow("select count(*... |
package main
func main() {
a := [...]int{
1, 2,
}
println(&a, &a[0], &a[1])
}
|
package test
import (
"fmt"
"gengine/builder"
"gengine/context"
"gengine/engine"
"reflect"
"strings"
"testing"
"time"
)
type Container struct {
//此处不带任何字段,就可以确保container指针的函数附带的是无状态函数(因为没有状态共享)
//这样注入的时候也可以少写很多代码
}
// Log
func (c *Container) LogModel() {
}
// nil
func (c *Container) IsNil(a interface{}) ... |
package flags
type Flags struct {
Verbose bool
InputPath string
OutputPath string
Clean bool
}
|
// +build !debug
/*
* Copyright (c) 2018 QLC Chain Team
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
package log
import (
"encoding/json"
"fmt"
"path/filepath"
"sync"
"time"
"github.com/qlcchain/go-qlc/common/util"
"github.com/qlcchain/go-qlc/config"
"... |
package main
import (
"fmt"
)
var arr = []interface{}{
"str", 1, nil,
}
func main() {
fl, ok := arr[1].(int)
fmt.Printf("%s %s", fl, ok)
}
|
package telemetry
import (
"net/http"
"runtime"
"time"
"github.com/pkg/errors"
"github.com/posthog/posthog-go"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/options"
)
const (
APIURL = "https://teleme... |
package hi
import (
//"../hello"
"fmt"
"math"
"math/rand"
//"os"
)
var print = fmt.Println
//var printAll = fmt.Println
//
//func test(name string, age int) (helloName string, helloAge int) {
// return name + string(age), age
//}
//
//func returnInt() int {
// return 1
//}
//
//func helloTest(name string, age i... |
package ast
// HasJoin is an AST node with join table.
type HasJoin interface {
AddJoin(Join)
}
|
package model
import (
"Seaman/utils"
"time"
)
type TplAppDataRoleT struct {
Id int64 `xorm:"pk autoincr BIGINT(20)"`
Name string `xorm:"not null comment('角色名称') VARCHAR(128)"`
Desp string `xorm:"not null comment('角色描述') VARCHAR(128)"`
Status int64 `xorm:"no... |
package main
import (
"fmt"
)
type User struct {
Id int
Name, Location string
}
func (u *User) Greetings() string {
return fmt.Sprintf("Hi %s from %s", u.Name, u.Location)
}
type Player struct {
User
GameId int
}
func main() {
p := Player{
User{
Id: 123213,
Name: "Matt",
Loc... |
package main
func payloadHandler(data PayloadCollection) {
for _, payload := range data.Payloads {
go payload.UploadToS3() // <----- DON'T DO THIS
}
}
|
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"time"
)
func recordMetric() {
for {
counterOps.Inc()
time.Sleep(1*time.Second)
}
}
func recordHistogramMetr... |
package miniporte
import (
"log"
"github.com/cenkalti/backoff"
irc "github.com/fluffle/goirc/client"
"github.com/oz/miniporte/epistoli"
link "github.com/oz/miniporte/link"
)
// Bot stores the state of our bot, and its configuration.
type Bot struct {
Chans []string
Config *irc.Config
Client *irc.Conn
Ctl ... |
/*
* Copyright 2020-present Open Networking Foundation
*
* 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 applicabl... |
package main
import (
"testing"
)
func BenchmarkInsert(b *testing.B) {
for i := 0; i < b.N; i++ {
b.Run("insert", func(bp *testing.B) { insert() })
}
}
func BenchmarkRead(b *testing.B) {
for i := 0; i < b.N; i++ {
b.Run("read", func(bp *testing.B) { read("ca5bd769-7b2c-40af-9d0b-5e370091ba8a") })
}
}
func ... |
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
str := "123455" //分配到只读内存段
fmt.Println("[]byte str:", []byte(str))
//var sli []byte
//获取字符串底层数组的指针
//strPtr := unsafe.Pointer(&(sli[0]))
//获取str中 Data指针
//p := (*reflect.StringHeader)(unsafe.Pointer(&str))
//获取字符串指向的底层数组地址
// strptr := unsafe.... |
/*
* Simplified interface for cloning an existing server.
*/
package main
import (
"encoding/hex"
"flag"
"fmt"
"log"
"os"
"path"
"strings"
"time"
"github.com/grrtrr/clcv2"
"github.com/grrtrr/clcv2/clcv2cli"
"github.com/grrtrr/exit"
"github.com/olekukonko/tablewriter"
)
func main() {
var net = flag.Str... |
package mysql
import (
"database/sql"
"github.com/Tanibox/tania-core/src/user/repository"
"github.com/Tanibox/tania-core/src/user/storage"
)
type UserAuthRepositoryMysql struct {
DB *sql.DB
}
func NewUserAuthRepositoryMysql(db *sql.DB) repository.UserAuthRepository {
return &UserAuthRepositoryMysql{DB: db}
}
... |
// การประกาศตัวแปร
package main
import "fmt"
func main() {
// ตัวแปร myAge รับค่าเป็น int
var myAge int = 200
// ถ้าใช้ := ไม่ต้องประกาศ var
// := คือ รับค่าโดยไม่ต้องกำหนดประเภท
myAge2 := 500
var something bool = true
// age1 = 35 and age2 = 44
age1, age2 := 35, 44
fmt.Println("Value Variable = ", myAge)
... |
/*
Copyright 2019 The Kubernetes 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, ... |
/*
* @File: models.movie.go
* @Description: Defines Movie information will be returned to the clients
* @Author: Nguyen Truong Duong (seedotech@gmail.com)
*/
package models
import "gopkg.in/mgo.v2/bson"
// Movie information
type Movie struct {
ID bson.ObjectId `bson:"_id" json:"id"`
Name ... |
package server
import (
"net"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
type override struct {
Header string
Match string
Host string
Path string
}
type config struct {
Path string
Host string
Override override
}
// BindProxy ...
func BindProxy() {
proxy := &httputil.ReverseProxy{
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.