text stringlengths 11 4.05M |
|---|
package testdata
import (
"context"
"github.com/frk/gosql"
"github.com/frk/gosql/internal/testdata/common"
)
type InsertReturningContextSliceQuery struct {
Users []*common.User `rel:"test_user:u"`
_ gosql.Return `sql:"*"`
ctx context.Context
}
|
/*
* @lc app=leetcode.cn id=198 lang=golang
*
* [198] 打家劫舍
*/
package main
import (
"fmt"
)
type ListNode struct {
Val int
Next *ListNode
}
func getIntersectionNode(headA, headB *ListNode) *ListNode {
if headA == nil || headB == nil {
return nil
}
a, b := headA, headB
for a != b {
... |
package transports
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/doniacld/outdoorsight/internal/endpoints"
"github.com/doniacld/outdoorsight/internal/endpoints/addspot"
"github.com/doniacld/outdoorsight/internal/endpoints/deletespot"
"github.com/doniacld/outdoorsight/internal/endpoin... |
// +build !race
package replication
import (
"testing"
"time"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/health"
"github.com/square/p2/pkg/health/checker/test"
"github.com/square/p2/pkg/labels"
"github.com/square/p2/pkg/manifest"
"github.com/square/p2/pkg/store/consul"
"github.com/square... |
package main
import (
"os"
"strconv"
"strings"
"time"
_ "image/png"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/faiface/pixel/text"
"golang.org/x/image/colornames"
)
var SM = pixel.IM.Scaled(pixel.ZV, FScale)
func Loop() {
cfg := pixelgl.WindowConfig{
Title: "Cryptodigger... |
package types
import (
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// NewDenom return a new denom
func NewDenom(id, name, schema string, creator sdk.AccAddress) Denom {
return Denom{
Id: id,
Name: name,
Schema: schema,
Creator: creat... |
package parser
import (
"fmt"
"testing"
)
func TestIsTargetHeader(t *testing.T) {
tests := []struct {
str string
expect bool
}{
{"aaa", false},
{"fds:main,fds,ff", true},
{"main: $(SRC", true},
}
for _, tt := range tests {
if tt.expect != isTargetDefinedLine(tt.str) {
t.Fatalf("%v should be %... |
package structures
import "github.com/goodwine/yaaji/tokenizer"
// Code represents a single piece of code that is equivalent in both AS3, and JS.
// ie. `x = -4 * a * c`
type Code struct {
Token tokenizer.Token
parent Structure
children []Structure
}
// Add checks the kind of structure that it was given, and... |
package Problem0321
func maxNumber(nums1 []int, nums2 []int, k int) []int {
size1 := len(nums1)
size2 := len(nums2)
res := make([]int, k)
var temp []int
// for 循环作用是,每次
// 从 nums1 中取 i 个数,得到temp1,在保证顺序的前提下,其值最大
// 从 nums2 中取 k-i 个数,得到temp2,在保证顺序的前提下,其值最大
// 把 temp1 和 temp2 混合成 temp,使其值最大。
// 记录 最大... |
package jwker
import (
"fmt"
"encoding/json"
"os"
)
type JWK struct {
KeyType string `json:"kty"`
}
func JwkToPem(jwkBytes []byte) string {
throwParseError("JWK parsing is not implemented yet :(")
return ""
}
func structToJWK(keyStruct interface{}) string {
jwk, err := json.Marshal(keyStruct)
if (e... |
package inttest
import (
"context"
"reflect"
"testing"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
"tagallery.com/api/config"
"tagallery.com/api/model"
"tagallery.com/api/mongodb"
"tagallery.com/api/testutil"
)
var categoryFixture = model.Category{
Name: ... |
package main
import (
"github.com/sharifanani/goWebApp/Pages"
"log"
"net/http"
)
func main() {
Pages.InitRoutes()
log.Fatal(http.ListenAndServe(":9909", nil))
}
|
package app
import (
"net/http"
"github.com/gorilla/mux"
meta "github.com/silverspase/todo/internal/modules/metadata/transport/gorilla-mux"
)
// TODO move router init to separate package (resolve cycle import issue)
func gorillaMuxRouter(t *App) http.Handler {
r := mux.NewRouter().StrictSlash(true)
r.HandleFun... |
package field
import (
"encoding/binary"
"io"
"github.com/tombell/go-serato/internal/decode"
"github.com/tombell/go-serato/internal/trim"
)
// Album is the album of the track.
type Album struct {
header *Header
data []byte
}
// Value returns te album.
func (f *Album) Value() string {
s := decode.UTF16(f.da... |
package main
import (
"bytes"
"fmt"
"net/http"
"os"
"time"
ui "github.com/gizak/termui/v3"
"github.com/u-root/webboot/pkg/menu"
"github.com/u-root/webboot/pkg/wifi"
"github.com/vishvananda/netlink"
)
// Collect stdout and stderr from the network setup.
// Declare globally because wifi.Connect() triggers
// ... |
package problem0342
import "testing"
func TestSolve(t *testing.T) {
t.Log(isPowerOfFour(16))
t.Log(isPowerOfFour(1))
t.Log(isPowerOfFour(6))
t.Log(isPowerOfFour(0))
}
|
/*
Copyright 2021. The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writ... |
package controller
import (
"github.com/gin-gonic/gin"
"secKill/proxy"
"secKill/resps"
"strings"
"time"
)
type SecRequest struct {
ProductId uint `form:"product_id" json:"product_id" binding:"required"`
UserId string `form:"user_id" json:"user_id" binding:"required"` // 用户ID
AccessTime tim... |
package main
/*type Queue []*Order
type Order struct {
priority int
quantity int
product string
customerName string
}
func (order *Order) New(priority int, quantity int, product string, customerName string) {
order.priority = priority
order.quantity = quantity
order.product = product
order.custo... |
package web_model
type WebsiteModel struct {
Id int64
WebsiteTitle string `xorm:"varchar(80)" json:"website_title"`
WebsiteUrl string `xorm:"varchar(255)" json:"website_url"`
WebsiteManager string `xorm:"varchar(30)" json:"website_manager"`
WebsiteNickname string `xorm:"varchar(50)" json:"website_nickname"`
Webs... |
package form
import (
"gorm.io/gorm"
"re/db/client"
)
type Domain struct {
gorm.Model
Name string
}
type DomainBridge struct { // domain -> domain
From int
To int
Name string
Code string
Constructor string
}
func init() {
client.DB.AutoMigrate(&DomainBridge{}, &Domain{})
}
|
package logs
import (
"fmt"
"log"
"strings"
"github.com/astaxie/beego/logs"
)
const (
AdapterConsole = "console"
AdapterFile = "file"
AdapterMultiFile = "multifile"
AdapterMail = "smtp"
AdapterConn = "conn"
AdapterEs = "es"
AdapterJianLiao = "jianliao"
AdapterSlack = "slack"
... |
package main
import (
"errors"
"fmt"
)
// multiple arguments acceptance
func callMe(params ...interface{}) {
fmt.Println("Length: ", len(params))
}
func sum(x, y int) int {
return x + y
}
// return multiple types
func add(x, y string) (string, int) {
r := x + y
return r, len(r)
}
// named return type
func co... |
package main
import (
"LogTransfer/conf"
"LogTransfer/es"
"LogTransfer/kafka"
"fmt"
"gopkg.in/ini.v1"
)
// LogTransfer
// 将日志数据从Kafka中取出来,发往ElasticSearch
func main() {
// 加载配置文件
var cfg conf.LogTransferCfg
// 因为go里面修改是需要传递引用地址,所以需要用 &cfg
// 需要注意:在一个函数修改变量的时候,一定要传递一个指针
// 与配置文件对应的结构体中,一定要设置tag(特别是嵌套结构体)
err... |
package main
import (
"fmt"
)
func combSort(items []int) {
var (
n = len(items)
gap = len(items)
shrink = 1.3
swapped = true
)
for swapped {
swapped = false
gap = int(float64(gap) / shrink)
if gap < 1 {
gap = 1
}
for i := 0; (i + gap) < n; i++ {
if items[i] > items[i+gap] {
... |
package arangodb
func (c *Connection) ListGraphs() {
}
|
package gitcomm
import (
"bytes"
"fmt"
)
// Message type holds all commit message fields
type Message struct {
// Type message field
Type string
// Subject message field
Subject string
// Body message field
Body string
// Foot message field
Foot string
}
func (m Message) String() string {
buf := bytes.New... |
package main
import (
"github.com/opencontainers/runtime-tools/validation/util"
)
func main() {
g, err := util.GetDefaultGenerator()
if err != nil {
util.Fatal(err)
}
g.SetProcessApparmorProfile("acme_secure_profile")
err = util.RuntimeInsideValidate(g, nil, nil)
if err != nil {
util.Fatal(err)
}
}
|
package middleware
import "net/http"
type (
middlewareFunc func(http.HandlerFunc) http.HandlerFunc
middleware []middlewareFunc
)
// Chain ...
func Chain(mw ...middlewareFunc) middleware {
return middleware(mw)
}
// Then ...
func (m middleware) Then(h http.HandlerFunc) http.HandlerFunc {
for i := range m {
... |
package task
import (
"context"
"fmt"
"io"
"os"
"sync/atomic"
"github.com/go-task/task/v2/internal/compiler"
compilerv1 "github.com/go-task/task/v2/internal/compiler/v1"
compilerv2 "github.com/go-task/task/v2/internal/compiler/v2"
"github.com/go-task/task/v2/internal/execext"
"github.com/go-task/task/v2/int... |
package user
import (
"encoding/json"
"errors"
"fmt"
"math"
"sync"
"sync/atomic"
"github.com/Quaqmre/mirjmessage/logger"
)
// // Service OutDoor tho user service
// type Service interface {
// NewUser(name, password string) (*User, error)
// }
// ErrorInvalidContext using when user or password is nil
var E... |
package main
import (
"fmt"
"github.com/yoshinorihisakawa/qiita-batch/domain/service"
"github.com/yoshinorihisakawa/qiita-batch/infrastructure"
"github.com/yoshinorihisakawa/qiita-batch/usecase"
"time"
"os"
log "github.com/sirupsen/logrus"
"github.com/yoshinorihisakawa/qiita-batch/conf"
)
func init() {
// Lo... |
package agent
import (
"strconv"
"github.com/mee6aas/kyle/internal/pkg/pool"
)
// Config holds the configuration for the agent.
type Config struct {
Host string
Port uint16
}
// Setup initializes the agent.
func Setup(conf Config) (e error) {
serveHost = conf.Host
servePort = strconv.Itoa(int(conf.Port))
ser... |
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestUpload(t *testing.T) {
r, _ := http.NewRequest("POST", "http://localhost/upload", nil)
w := httptest.NewRecorder()
uploadHandler(w, r)
if w.Code != http.StatusOK {
t.Errorf("Expected %d, get %d", http.StatusOK, w.Code)
t.Error(w.Bo... |
package compute
import (
"testing"
"github.com/megamsys/opennebula-go/api"
"gopkg.in/check.v1"
)
func Test(t *testing.T) {
check.TestingT(t)
}
type S struct{}
var _ = check.Suite(&S{})
func (s *S) TestCreate(c *check.C) {
//oneadmin:yourWuOtHij3
client, _ := api.NewRPCClient("http://103.56.92.4:2633/RPC2",... |
package keeper
import (
"encoding/json"
"strings"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/ethermint/x/escrow/types"
)
func (k Keeper) EscrowCoin(ctx sdk.Context, buyer sdk.AccAddress, amount sdk.Coins) error {
// TODO: Support o... |
package gameobjects
var ItemsCacheMap map[int]*Item
type Item struct {
ItemInGameID int
ItemBaseID int
ItemName string
ItemTypeID int
WearAttribute string
ItemLocation string
ItemParameters map[string]float32
}
func NewItem(ItemBaseID int) *Item{
getItem := new(Item)
getItem.ItemBaseID = ItemBaseID
getItem... |
package cmd
import (
"fmt"
"os"
"strings"
"github.com/grrtrr/clcv2"
"github.com/grrtrr/exit"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
func init() {
Root.AddCommand(&cobra.Command{
Use: "nets [location]",
Aliases: []string{"networks", "net"},
Short: "Show available networks"... |
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... |
package epic
import (
"log"
"github.com/google/go-github/github"
"github.com/karen-irc/popuko/operation"
)
func AssignReviewer(client *github.Client, ev *github.IssueCommentEvent, assignees []string) (bool, error) {
log.Printf("info: Start: assign the reviewer by %v\n", *ev.Comment.ID)
defer log.Printf("info: E... |
package genesis
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"database/sql"
"encoding/hex"
"os"
"reflect"
"testing"
"github.com/SIGBlockchain/project_aurum/internal/block"
"github.com/SIGBlockchain/project_aurum/internal/blockchain"
"github.com/SIGBlockchain/project_aurum/internal/constants"
"g... |
package problem0300
func lengthOfLISII(nums []int) int {
n := len(nums)
if n <= 1 {
return n
}
list := []int{nums[0]}
for i := 1; i < n; i++ {
l, r := 0, len(list)-1
for l <= r {
mid := (l + r) / 2
if nums[i] > list[mid] {
l++
} else {
r--
}
}
if l >= len(list) {
list = append(lis... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/8/25 8:52 下午
# @File : lt_34_在排序数组中查找第一次和最后一次出现的元素.go
# @Description :
# @Attention :
*/
package offer
func searchRange(nums []int, target int) []int {
if len(nums) == 0 {
return []int{-1, -1}
}
r := []int{-1, -1}
r[0] = searchRangeHalf(nums, target, tr... |
package service
import "context"
type ServerMock struct {
ListenAndServeFunc func(context.Context) <-chan []error
}
func (sm *ServerMock) ListenAndServe(ctx context.Context) <-chan []error {
return sm.ListenAndServeFunc(ctx)
}
|
package main
import "fmt"
// https://leetcode-cn.com/problems/edit-distance/
// -----------------------------------------------------------------------------
// 编辑距离
// 设 D(i,j) 为字符串 S[0..i] 和 T[0..j] 的编辑距离
// 1. 考虑 D(0,0):
// a. S[0] == T[0], 则 D(0,0) = 0, 无需改动
// b. S[0] != T[0], 则 D(0,0) = 1, 替换S[0]为T[0], 或者替... |
package easypost
import (
"context"
"net/http"
)
// TrackingLocation provides additional information about the location of a
// tracking event.
type TrackingLocation struct {
Object string `json:"object,omitempty"`
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
Country string `j... |
package todolist
type Printer interface {
//Print(*GroupedTodos, bool)
PrintReport(*Report, []*Todo)
}
|
package sweetiebot
import (
"database/sql"
"fmt"
"strconv"
"strings"
"time"
"github.com/blackhole12/discordgo"
_ "github.com/go-sql-driver/mysql"
)
type BotDB struct {
db *sql.DB
status AtomicBool
lastattempt time.Time
log L... |
package databases
var (
Database PostgresDB
)
|
package covfefe
import (
"encoding/json"
"fmt"
"os"
"github.com/FiloSottile/mostly-harmless/covfefe/internal/twitter"
)
func getMessage(token []byte) interface{} {
var data map[string]json.RawMessage
err := json.Unmarshal(token, &data)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", token)
panic(err)
}
... |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this fi... |
package service
import (
"regexp"
"time"
"github.com/ch3lo/overlord/monitor"
)
type ConstraintsParams struct {
ImageName string
MinInstancesPerCluster map[string]int
}
// Parameters es una estructura que encapsula los parametros
// de configuración de un nuevo servicio
type Parameters struct {
ID... |
package lib
import (
"fmt"
)
// A Painter can draw anythings to display
type Painter interface {
// Draw is drawing for character or graphics
Draw()
}
// CharacterPainter can draw a character
type CharacterPainter struct {
character rune
}
// NewCharacterPainter creates *Painter from character
func NewCharacter... |
package go39
import (
"bytes"
"encoding/binary"
"fmt"
"math"
)
//NetIO network input/ output
type NetIO struct {
writeBuffer bytes.Buffer
readBuffer bytes.Buffer
}
//PushByte - Write a byte
func (n *NetIO) PushByte(value int32) {
log.Debugf("writing byte %d", value)
n.writeBuffer.WriteByte(byte(value & 0xFF... |
//Поэтому, когда вы размещаете заказ с «fillOrKill», он не будет (не должен) создавать заказ, если он не может быть полностью заполнен.
//Поэтому, если вы установили цену заказа, которая не указана в книге заказов, заказ будет прерван (заказ не будет размещен).
//Этот флаг делает ваш заказ «только» (более высокие сборы... |
package reg
import "testing"
func TestSetRegisterIdentity(t *testing.T) {
rs := []Register{
NewVirtual(42, KindGP, B32),
NewVirtual(43, KindGP, B32),
NewVirtual(42, KindVector, B32),
NewVirtual(42, KindGP, B64),
AL, AH, CL,
AX, R13W,
EDX, R9L,
RCX, R14,
X1, X7,
Y4, Y9,
Z13, Z31,
}
s := NewEmp... |
// 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 main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"strings"
"time"
"../proto"
)
const (
MaxRead = 4096
)
type Login struct {
Cmd string `json:"cmd"`
SeqId string `json:"seqId"`
Mac string `json:"mac"`
Token string `json:"token"`
}
func LoginFunc() ([]byte, uint32) {
login := Login{
... |
package main
import (
"fmt"
"time"
)
func debounce(interval time.Duration, done chan<- struct{}, input <-chan int, f func(arg int)) {
var (
item int
timeout = time.After(interval)
)
for {
select {
case item = <-input:
if item % 100000 == 0 {
fmt.Println("received a send on a spammy channel - might... |
package utils
//用户Id字段名称
const USER_ID_FILED string = "userId"
//超级管理员Id
const SUPER_ADMIN_USER_ID = 1
|
package natss
import (
"context"
"crypto/rand"
"encoding/hex"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/stan.go"
"github.com/nats-io/stan.go/pb"
"github.com/pkg/errors"
"github.com/utilitywarehouse/go-pubsub"
)
func generateID() string {
random := []byte{0, 0, 0, 0, 0, 0, 0, 0}
_, err := ran... |
package main
import (
"encoding/json"
"fmt"
)
type UserInfo struct {
UserID int
UserName string
IsStudent bool
}
// 定义struct时加上tag会自动转成tag的名称
type UserInfoWithTag struct {
UserID int `json:"user_id"`
UserName string `json:"user_name"`
IsStudent bool `json:"is_student"`
}
type Role struct {
Rol... |
package lpcodecs
import (
"bytes"
"fmt"
"sort"
"time"
"github.com/influxdata/line-protocol/v2/lineprotocol"
"github.com/influxdata/line-protocol-corpus/lpcorpus"
)
type lineProtocolV2Decoder struct{}
func (lineProtocolV2Decoder) Decode(input *lpcorpus.DecodeInput) ([]*lpcorpus.Point, error) {
dec := linepro... |
package main
import (
"fmt"
"sync"
"time"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/plugin"
"github.com/pkg/errors"
)
type Plugin struct {
plugin.MattermostPlugin
configurationLock sync.RWMutex
configuration *configuration
run bool
}
func (p *Plugin)... |
package controller
import (
"encoding/json"
"fmt"
"im/app/service"
"log"
"net/http"
"strconv"
"sync"
"github.com/gorilla/websocket"
)
type Node struct {
Conn *websocket.Conn
// 并行转串行
DataQueue chan []byte
GroupSets set.Interface
}
var clientMap map[int64]*Node = make(map[int64]*Node, 0)
// 读写锁
var rwlo... |
package main
import (
"fmt"
)
func main() {
testMakeInit()
testDirectInit()
testMap()
//测试查找
testQuery()
//测试遍历
testTraverse()
//测试删除
testDelete()
//测试切片
testSlice()
}
func testMakeInit() {
a := make(map[string]string, 10)
a["1"] = "1"
a["2"] = "2"
a["3"] = "3"
a["3"] = "3"
fmt.Println(a)
}
fun... |
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
text := input.Text()
if text == "null" {
break
}
counts[text]++
}
for line, value := range counts {
if value > 1 {
fmt.Printf("%s\t%d\n", line, value)... |
package informer
import (
"context"
"sort"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func Test_informer(t *testing.T) {
var list []Object[int]
var lw ListAndWatch[int] = &PollListAndWatch[int]{
ListFunc: func(ctx context.Context) ([]Object[int], error) {
return list, nil
},
PollPeriod:... |
package cache
import (
"fmt"
"testing"
)
func TestLRUCache(t *testing.T) {
c := NewLRUCache(5)
fmt.Println("len:", c.Size())
c.Set(1, 1)
c.Set(2, 2)
c.Set(3, 3)
c.Set("a", "a")
c.Set("b", "b")
fmt.Println("len:", c.Size())
for e := c.list.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
fmt.Pri... |
package gdw
import (
"fmt"
"testing"
)
func TestBatch(t *testing.T) {
test := adder{count: 0}
pool := NewWorkerPool(3)
defer pool.Close()
batch1 := pool.NewTempBatch()
batch2 := pool.NewTempBatch()
pool.NewBatch("my batch")
defer batch1.Clean()
defer batch2.Clean()
defer pool.CleanBatch("my batch")
batch1... |
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("main function starts here")
c := make(chan string)
go func() {
time.Sleep(time.Second * 5)
c <- "it's c channel"
}()
select {
case res := <-c:
fmt.Println(res)
case <-time.After(6 * time.Second):
fmt.Println(time.Second)
}
}
|
// Copyright (c) 2017 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package walletdbtest
// Tester is an interface type that can be implemented by *testing.T. This
// allows drivers to call into the non-test API using their own test context... |
//go:build mage
// +build mage
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path"
"strings"
"github.com/magefile/mage/mg"
mageextras "github.com/mcandre/mage-extras"
"github.com/mcandre/stank"
)
// artifactsPath describes where artifacts are produced.
var artifactsPath = "bin"
//... |
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
// mysql 드라이버를 사용하여, 데이터베이스에 접속
// 사용자: testuser, 비밀번호: testpass, URL
db, err := gorm.Open("mysql", "testuser:testpass@tcp(127.0.0.1:3306)/")
if err != nil {
log.Fatal(err)
}
defer db.Close()
va... |
package handlers
import (
"net/http"
"github.com/roger-king/go-ecommerce/pkg/utilities"
"github.com/roger-king/go-ecommerce/pkg/models"
"encoding/json"
)
func AuthenticateController(w http.ResponseWriter, req *http.Request) {
var user models.User
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(... |
package providers
import (
"context"
"encoding/binary"
"fmt"
"strings"
"time"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
lru "gx/ipfs/QmQjMHF8ptRgx4E57UFMiT4YM6kqaJeYxZ1MCDX23aw4rK/golang-lru"
cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
goprocess "gx/... |
package download
import (
"os/exec"
"os"
)
// Download
func Run(options Options) {
// Set the commands.
download := "curl -OL http://wordpress.org/latest.tar.gz && "
unzip := "tar xzf latest.tar.gz && "
relocate := "mv wordpress/* "+ options.Destination +" && "
cleanup := "rm -rf latest.tar.gz wordpress;"
/... |
package main
import (
"fmt"
"os"
"encoding/gob"
"bufio"
)
type Address struct {
Type string
City string
Country string
}
type VCard struct {
FirstName string
LastName string
Addresses []*Address
Remark string
}
var content string
var vc VCard
func main() {
file, _ := os.Open("vcard.gob")
defer file.Cl... |
// Copyright 2016 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... |
// Copyright 2020 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package canvas
import (
"encoding/binary"
"image/color"
"math"
)
type buffer struct {
bytes []byte
error error
}
var byteOrder = binary.BigEndian
func (... |
package apigen
import (
"fmt"
)
var patchLibFn string
// WritePatchAPIToLib - This writes the patch api libary defination into lib file
func WritePatchAPIToLib(apimodel API) {
patchLibFn = ""
createPatchAPILibFuncStart(apimodel)
createPatchAPILibFuncParams(apimodel)
createPatchAPILibFuncBody(apimodel)
ReplaceF... |
/* SPDX-License-Identifier: Apache-2.0
* Copyright (c) 2020 Intel Corporation
*/
package ngcnef
// PfdContent represents the content of a PFD for an application identifier.
type PfdContent struct {
// Identifies a PDF of an application identifier.
PfdID string `json:"pfdID,omitempty"`
// Represents a 3-tuple with... |
package testdata
import (
"time"
"github.com/frk/gosql"
"github.com/frk/gosql/internal/testdata/common"
)
type DeleteWithReturningSliceErrorHandlerQuery struct {
Users []*common.User `rel:"test_user:u"`
Where struct {
CreatedBefore time.Time `sql:"u.created_at <"`
}
_ gosql.Return `sql:"*"`
eh common.Erro... |
package conf
import (
"encoding/json"
"fmt"
"io/ioutil"
)
//定义配置文件解析后的结构
type JQConfig struct {
DB_addr string
DB_port string
DB_name string
DB_username string
DB_password string
TB_prefix string
Code string
Unit string
JQ_mob string
JQ_pwd string
}
/*
"db_addr":"127.0.0.1", //db的地址
... |
package main
import (
"fmt"
"goUtils/learn/interface/multiInter"
)
type T struct {
aa int
bb string
}
type T2 struct {
aa2 int
bb2 string
}
func (t T) M1() { println("IMY******* M1", t.bb) }
func (T) M2() { println("IMY******* M2") }
func (T2) M2() { println("IMY******* M2") }
func f1(i multiInter.I1) { i... |
// 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 lhttp
import (
"errors"
"net/url"
"strings"
)
func hostRequiresSSL(host string) bool {
host = strings.ToLower(host)
return strings.HasSuffi... |
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
// Error to be reported to the user
type Error struct {
Name string `json:"errorName"`
Desciption string `json:"errorDescription"`
}
// Hint to be shown to the user.
type Hint struct {
... |
package main
import "fmt"
func addUpper() func(int) int {
var n int = 10
return func(x int) int {
n += x
return n
}
}
func playerGen(name string) func() (string, int) {
hp := 150
// 返回创建的闭包
return func() (string, int) {
// 将变量引用到闭包中
return name, hp
}
}
func main() {
s := addUpper()
fmt.Println(s(1... |
package main
func collatzSequence(n int) []int {
sequence := make([]int, 0)
for n > 1 {
sequence = append(sequence, n)
if n%2 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
}
return append(sequence, 1)
}
|
package config
//Configuration file
type Configuration struct {
Dev struct {
PORT string `json:"PORT"`
Imageurl string `json:"imageurl"`
Email string `json:"email"`
Password string `json:"password"`
} `json:"dev"`
Production struct {
PORT string `json:"PORT"`
Imageurl string `json:"imageurl"`... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
package main
import (
"log"
"github.com/parnurzeal/gorequest"
)
type FacebookRes struct {
Message struct {
Text string `json:"text"`
} `json:"message"`
Recipient struct {
ID int64 `json:"id"`
} `json:"recipient"`
}
func post_facebook(msg string, id int64 ) {
request := gorequest.New()
var send Facebook... |
package user
import (
"encoding/json"
"fmt"
"net/http"
"github.com/dgrijalva/jwt-go"
)
type User struct {
Email string `json:"email"`
Password string `json:"password"`
}
type AuthToken struct {
TokenType string `json:"token_type"`
Token string `json:"access_token"`
ExpiresIn int64 `json:"expires_in... |
package main
import "fmt"
func main() {
getSum := getSumFunction()
fmt.Println(getSum(1, 2, 3, 4, 5, 6, 7, 8, 9))
}
func getSumFunction() func(...int) int {
return func(xi ...int) int {
total := 0
for _, v := range xi {
total += v
}
return total
}
} |
package main
import (
"github.com/dublour/genesis_se_task3/internal/server"
)
func main() {
server.main()
} |
package main
import (
_ "auth/routers"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func init() {
beego.SetLogger("file", `{"filename":"./log/auth.log"}`)
beego.SetLogFuncCall(true)
beego.BeeLogger.DelLogger("console")
mysqlUser := beego.AppConfig.String("mys... |
package tfc
import (
"fmt"
"regexp"
"github.com/hyperledger/fabric/core/chaincode/shim"
tfcPb "github.com/stefanprisca/strategy-protobufs/tfc"
)
func handleDev(APIstub shim.ChaincodeStubInterface, creatorSign []byte,
gameData tfcPb.GameData, payload tfcPb.BuildTrxPayload) (tfcPb.GameData, error) {
err := asse... |
package api
import (
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/azzzak/fakecast/fs"
"github.com/azzzak/fakecast/store"
"github.com/go-chi/chi"
)
type ctxKey int
const (
// CID id of a channel
CID ctxKey = iota + 1
// PID id of a podcast
PID
)
// Cfg configuration
type Cfg st... |
package cbnet
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
dataobjects "github.com/cloud-barista/cb-larva/poc-cb-net/internal/cb-network/data-objects"
"github.com/cloud-barista/cb-larva/poc-cb-net/internal/file"
ipchkr "github.com/cloud-bari... |
// INTEGRATION TESTS
package kafka_test
import (
"fmt"
"testing"
"time"
confluent "github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/etf1/kafka-message-scheduler-admin/server/helper"
"github.com/etf1/kafka-message-scheduler-admin/server/store"
"github.com/etf1/kafka-message-scheduler-admin/server/s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.