text stringlengths 11 4.05M |
|---|
package main
import "fmt"
type Test struct {
}
func (t *Test) print() {
for i := 0; i <= 10; i++ {
for j := 0; j <= 8; j++ {
fmt.Print("*")
}
fmt.Print("\n")
}
}
func (t *Test) print2(n, m int) {
for i := 0; i <= n; i++ {
for j := 0; j <= m; j++ {
fmt.Print("*")
}
fmt.Print("\n")
}
}
func (t *T... |
package lb_handler
import (
"dynamicpath/src/load_balancer/lb_context"
"dynamicpath/src/load_balancer/lb_util"
"dynamicpath/src/load_balancer/logger"
"fmt"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
var HandlerLog *logrus.Entry
func init() {
// init Pool
HandlerLog = logger.HandlerLog
}
func Handle(... |
package paxos
import
(
"net"
)
type Paxos struct {
nodes []string
}
func (paxos*Paxos) AddNode(title string){
paxos.nodes = append(paxos.nodes, title)
} |
package main
import (
"fmt"
"io/ioutil"
)
func main() {
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n\n", string(contents))
}
/**
go 的 if else 写法
*/
var (
contents2 []byte
err2 error
)
if contents2, err2 = i... |
package compare
func Test() {
ch1 := make(chan int)
ch2 := make(chan int)
defer close(ch1)
defer close(ch2)
defer close(ch2)
defer close(ch2)
defer close(ch2)
defer close(ch2)
defer close(ch2)
defer close(ch2)
}
|
// Clock stub file
// To use the right term, this is the package *clause*.
// You can document general stuff about the package here if you like.
package clock
import "fmt"
// The value of testVersion here must match `targetTestVersion` in the file
// clock_test.go.
const testVersion = 4
// Clock API as stub definit... |
package main
import (
"fmt"
"github.com/trustmaster/goflow"
)
type Greeter struct {
flow.Component
Name <-chan string
Res chan<- string
}
func (g *Greeter) OnName(name string) {
greeting := fmt.Sprintf("Hello, %s!", name)
g.Res <- greeting
}
type Printer struct {
flow.Component
Line <-chan string
}
func... |
package main
import (
"fmt"
"log"
"math/rand"
"time"
"net/http"
_ "net/http/pprof"
)
const (
maxDigit int = 6
)
type signalData struct {
signal []int
status string
}
func main() {
c := make(chan signalData)
go sender(c)
go receiver(c)
log.Println(http.ListenAndServe("localhost:6060", nil))
}
func s... |
package main
import (
"log"
"sync"
)
func generate(nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, num := range nums {
log.Printf("[g-goroutine] publishing number : %d \n", num)
out <- num
}
}()
return out
}
func square(id int, inputC <-chan int) <-chan int {
... |
package images
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/dollarshaveclub/acyl/pkg/eventlogger"
"github.com/dollarshaveclub/acyl/pkg/ghclient"
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/jsonmessag... |
package utils
import (
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)
var Logger *logs.BeeLogger
// 保证此文件最早加载
// 初始化日志
func init() {
runmode := strings.TrimSpace(strings.ToLower(beego.AppConfig.DefaultString("runmode", "dev")))
if runmode == "dev" {
Logger = logs.NewLogger(1)
Logger... |
package sql
import (
"github.com/yydzero/mnt/executor"
"log"
"net"
)
// connstr for libpq connection
type ConnectionArgs struct {
Database string
User string
ClientEncoding string
DateStyle string
}
// Session contains the state of a SQL client connection.
type Session struct {
Database ... |
package server
import (
"context"
"fmt"
"log"
config "github.com/chutommy/metal-price/metal/config"
data "github.com/chutommy/metal-price/metal/service/data"
metal "github.com/chutommy/metal-price/metal/service/protos/metal"
)
// Metal is a the service server.
type Metal struct {
log *log.Logger
prices *d... |
package message
import (
"bytes"
"io"
)
const (
// MsgUnknown unknown message
MsgUnknown = iota
// MsgResult result message
MsgResult
// MsgAuth authenticate message
MsgAuth
// MsgData data message
MsgData
// MsgAck ack message
MsgAck
)
// for simple, using json for exchange message
type Marshler interfa... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package export
import (
"database/sql"
"fmt"
"regexp"
"strings"
"text/template"
"github.com/pingcap/errors"
tcontext "github.com/pingcap/tidb/dumpling/context"
)
const (
outputFileTemplateSchema = "schema"
outputFileTemplateTable = "table"
ou... |
package qx
import "strings"
type FunctionInfo struct {
Schema string
Name string
Alias string
Arguments []interface{}
}
// ToSQL marshals a FunctionInfo into an SQL query.
func (f *FunctionInfo) ToSQL() (string, []interface{}) {
return f.ToSQLExclude(nil)
}
// ToSQL marshals a FunctionInfo into an ... |
// Copyright 2015-2018 trivago N.V.
//
// 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 ... |
package base
import "errors"
var (
NoReadTokenError = errors.New("This Warp10 call need a READ token access on the data")
NoWriteTokenError = errors.New("This Warp10 call need a WRITE token access on the data")
) |
package main
import (
"fmt"
"io"
"log"
"os"
)
func main() {
// experimentWriteToFileUsingFPrintf()
experimentReadFromCertainOffsetInFile()
}
func experimentReadFromCertainOffsetInFile() {
file, err := os.Open("./dicky")
if err != nil {
log.Panicf("error in opening file, err: %v", err)
}
offset := 1
var... |
// Copyright (c) 2020 Tailscale Inc & 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 tstest
import (
"log"
"os"
"testing"
)
type testLogWriter struct {
t *testing.T
}
func (w *testLogWriter) Write(b []byte) (int, error... |
package config
import (
"laravel-go/pkg/orm/config"
"github.com/spf13/viper"
)
type DBConfig struct {
Default string
Connections map[string]config.ConnParam
}
func NewDBConfig() *DBConfig {
return &DBConfig{
Default: viper.GetString("DB_CONNECTION"),
Connections: map[string]config.ConnParam{
"mysql"... |
package main
import (
"encoding/json"
"io/ioutil"
"log"
"github.com/golang/glog"
)
func ReadSwagger(swaggerFile string) SwaggerTemplate {
raw, err := ioutil.ReadFile(swaggerFile)
if err != nil {
log.Fatal(err)
}
_, isJson := isJson(string(raw))
if isJson {
var swagger SwaggerTemplate
j... |
package main
import "fmt"
func main(){
//Chained conditionals: adding more than one conditions onto the other
//Normal conditions
greaterThan := 5 < 6
fmt.Printf("%t", greaterThan)
//Operators for chaining conditionals
// || - or, && - and, ! not
} |
package _179_Largest_Number
import "testing"
func TestLargestNumber(t *testing.T) {
if ret := largestNumber([]int{10, 2}); ret != "210" {
t.Errorf("wrong ret with %s", ret)
}
if ret := largestNumber([]int{3, 30, 34, 5, 9}); ret != "9534330" {
t.Errorf("wrong ret with %s", ret)
}
if ret := largestNumber([]int... |
package main
import (
"flag"
"fmt"
"log"
"os"
"github.com/fvbock/endless"
"github.com/go-martini/martini"
"github.com/kyf/6ryim/util"
)
const (
CERT_FILE string = "../certs/6ry.crt"
KEY_FILE string = "../certs/6ry.key"
LOG_PATH string = "/var/log/6ryim_daemon/6ryim_daemon.log"
LOG_PREFIX string = "[6r... |
package day01
import (
"strconv"
"../utils"
)
var input, _ = utils.ReadFile("day01/input.txt")
// ParseLines reads a file into a slice of int:s
func ParseLines(input []string) []int {
var expense []int
for _, s := range input {
i, _ := strconv.Atoi(s)
expense = append(expense, i)
}
return expense
}
// So... |
package config
import (
"os"
"encoding/json"
)
type Properties struct {
Server struct {
IP string `json:"ip"`
Port int `json:"port"`
} `json:"server"`
DataSource struct {
Sql struct {
Driver string `json:"driver"`
Url string `json:"url"`
} `json:"sql"`
} `json:"data_source"`
}
var props *Pr... |
package core
import (
"fmt"
"github.com/morhekil/goratio/analyser/timeframe"
)
// PropEvent is a concrete implementation of Prop, based on Events
type PropEvent struct {
name string
r *Repository
}
// Analyse performs the analysis of the prop over the given timeframe
func (p PropEvent) Analyse(t timeframe.Mo... |
// Copyright 2020 The Reed Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package p2p
import (
"github.com/reed/log"
"github.com/tendermint/tmlibs/common"
"net"
"strconv"
)
type Peer struct {
common.BaseServic... |
package main
import (
auth "github.com/anraku/echo-sample/auth"
handler "github.com/anraku/echo-sample/handler"
log "github.com/anraku/echo-sample/log"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
// Echo instance
e := echo.New()
// Middleware
e.Pre(middleware.Logger())
... |
package cmd
import (
"os"
"path"
"strings"
"testing"
"github.com/instructure-bridge/muss/config"
)
// helpers
var testbin string
func init() {
cwd, err := os.Getwd()
if err != nil {
panic("Failed to get current dir: " + err.Error())
}
testbin = path.Join(cwd, "..", "testdata", "bin")
}
func newTestConf... |
package slices
import (
"context"
"sync"
)
// AllAsync returns true if f returns true for all elements in slice.
//
// This is an asynchronous function. It will spawn as many goroutines as you specify
// in the `workers` argument. Set it to zero to spawn a new goroutine for each item.
func AllAsync[S ~[]T, T any](i... |
package pathfileops
import (
"os"
"strings"
"testing"
)
func TestFileOpenConfig_CopyIn_01(t *testing.T) {
expectedFOpenCode := os.O_WRONLY | os.O_APPEND | os.O_TRUNC
fOpCfg1, err := FileOpenConfig{}.New(FOpenType.TypeWriteOnly(),
FOpenMode.ModeAppend(), FOpenMode.ModeTruncate())
if err != nil {
... |
/*
Copyright 2021 CodeNotary, Inc. 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 law or agreed to i... |
package mat
type World struct {
Light []Light
AreaLight []AreaLight
Objects []Shape `yaml:"objects,flow"`
}
func NewDefaultWorld() World {
light := NewLight(NewPoint(-10, 10, -10), NewColor(1, 1, 1))
material := NewMaterial(NewColor(0.8, 1.0, 0.6), 0.1, 0.7, 0.2, 200)
s1 := NewSphere()
s1.Material = mate... |
package cache
import (
"fmt"
"os"
"path"
"time"
"log"
"github.com/go-co-op/gocron"
"github.com/pilillo/igovium/putters"
"github.com/pilillo/igovium/utils"
"xorm.io/xorm"
)
type dbHistoricizerType struct {
engine *xorm.Engine
}
func NewDBHistoricizer() *dbHistoricizerType {
return &dbHistoricizerType{}
}... |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func constructMaximumBinaryTree(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
mid := findIndexOfMax(nums)
left := nums[0:mid]
right := nums[(mid + 1):len(nums)]
r... |
package main
import (
"fmt"
"net"
"os"
"os/exec"
)
func keeprun(cmd *exec.Cmd) {
START:
err := cmd.Start()
if err != nil {
fmt.Println(err)
}
fmt.Println(cmd.Process)
cmd.Wait()
dumpcmd := exec.Command(cmd.Path, cmd.Args...)
dumpcmd.Stdout = os.Stdout
dumpcmd.Stderr = os.Stderr
dumpcmd.ExtraFiles = cm... |
package redismgr
import (
"common/clog"
"gopkg.in/redis.v4"
)
var RedisClust *redis.ClusterClient
var log = clog.GetLogger()
func GetRedisCluster() *redis.ClusterClient {
return RedisClust
}
func ConnectRedisCluster(addr []string) {
RedisClust = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: addr,
})
... |
package server
import (
"github.com/kardianos/service"
)
var logger service.Logger
type sol struct {
}
func (s *sol) Start(srv service.Service) error {
go StartServer()
return nil
}
func (s *sol) Stop(srv service.Service) error {
return nil
}
//InstallService install sleep on lan as a service in current os
fu... |
package types
// Side of an order
type Side int
const (
// Buy order
Buy Side = iota
// Sell order
Sell
)
// String returns the string name of the Side
func (s Side) String() string {
if int(s) == int(Buy) {
return "Buy"
}
return "Sell"
}
// OrderType of an order
type OrderType int
const (
// Limit orde... |
package session
type Manager interface {
Add(string) (string, error)
Get(string) (string, error)
}
|
package main
import "fmt"
/*
@Time : 2020/8/12 20:32
@Author : DELL ricemarch@foxmail.com
@tips:
*/
func wordBreak(s string, wordDict []string) bool {
set := make(map[string]bool)
maxlen := 0
for _, v := range wordDict {
set[v] = true
if len(v) > maxlen {
maxlen = len(v)
}
}
dp := make([]int, len(s))
... |
package main
import (
"sync"
"time"
)
const (
timeformat = "2006-01-02 15:04:05"
timeformatMetro = time.RFC3339
dataFormat = `{"ID":"%d", "time":"%s", "type":"%s", "value":"%.2f"}`
dataFormatMetro = `{"id":%d,"time":"%s","type":[{"name":"%s","value":%.2f,"range":{"min":%d,"max":%d,"delta":1,"time":%d... |
package labels
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// label the object with the first non-empty value, if all value are empty, it is not set at all
func Label(obj metav1.Object, name string, values ...string) {
for _, value := range values {
if value == "" {
continue
}
labels := obj.Ge... |
package commands
import (
"fmt"
"strings"
"github.com/go-crypt/crypt"
"github.com/go-crypt/crypt/algorithm"
"github.com/spf13/cobra"
"github.com/authelia/authelia/v4/internal/authentication"
"github.com/authelia/authelia/v4/internal/configuration"
"github.com/authelia/authelia/v4/internal/configuration/schem... |
package ui
import (
"fmt"
"strings"
"github.com/rivo/tview"
)
func (a *App) Live() (*tview.List, error) {
matches, err := a.be.GetLiveMatches()
if err != nil {
return nil, err
}
list := tview.NewList()
for i, m := range matches {
var rh, dh []string
for _, p := range m.Players {
if p.IsRadiant {
... |
/*
Description
The sequence of n − 1 consecutive composite numbers (positive integers that are not prime and not equal to 1) lying between two successive prime numbers p and p + n is called a prime gap of length n. For example, ‹24, 25, 26, 27, 28› between 23 and 29 is a prime gap of length 6.
Your mission is to wri... |
package model
import "time"
const (
SexWomen = "W"
SexMan = "M"
SexUnKnown = "U"
)
type User struct {
Id int64 `xorm:"pk autoincr bigint(64)" from:"id" json:"id"`
Mobile string `xorm:"varchar(20)" from:"mobile" json:"mobile"`
Passwd string `xorm:"varchar(40)" from:"passwd" json:"_"`
... |
/*
* Copyright The Titan Project Contributors.
*/
package forwarder
type Capability struct {
Scope string
}
type CreateVolumeRequest struct {
Name string
Opts map[string]interface{}
}
type GetPathResponse struct {
Err string
Mountpoint string
}
type GetVolumeResponse struct {
Err string
Volume V... |
package web
import (
"fmt"
"testing"
"time"
"github.com/mgutz/ansi"
_ "github.com/GoAdminGroup/go-admin/adapter/gin"
_ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql"
_ "github.com/GoAdminGroup/themes/adminlte"
"github.com/sclevine/agouti"
)
type Testers func(t *testing.T, page *Page)
type Serv... |
package kong
import (
"io/ioutil"
"net/http"
"strings"
)
const (
nodeInfo = "/"
status = "/status"
service = "/service"
)
type Admin struct {
adminUrl string
}
func New(adminUrl string) *Admin {
// remove trailing slash as our endpoint constants (see above)
// already has leading slashes
if strings.Has... |
package log
import (
"github.com/feng/future/go-kit/agfun/agfun-server/service"
)
//LoggingMiddleware 日志中间件
func LoggingMiddleware() service.SvcMiddleware {
return func(next service.AppService) service.AppService {
return logmw{next}
}
}
type logmw struct {
service.AppService
}
|
package util
import (
"net"
"testing"
)
func TestIPv4ToUint32(t *testing.T) {
tests := []struct{
ip net.IP
res uint32
} {
{ net.IPv4(0, 0, 0, 0), 0 },
{ net.IPv4(1, 1, 1, 1), 16843009 },
{ net.IPv4(10, 192, 50, 1), 180367873 },
}
for _, test := range tests {
if res := IPv4ToUint32(test.ip); res != ... |
package ircserver
import (
"testing"
"github.com/robustirc/robustirc/internal/robust"
"gopkg.in/sorcix/irc.v2"
)
func TestServerInvite(t *testing.T) {
i, ids := stdIRCServerWithServices()
i.ProcessMessage(&robust.Message{Session: ids["secure"]}, irc.ParseMessage("JOIN #test"))
mustMatchIrcmsgs(t,
i.Proces... |
package model
import (
"github.com/golang/protobuf/ptypes/timestamp"
protobuf "github.com/oojob/protobuf"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// EmailModel email
type EmailModel struct {
Email string `bson:"email,omitempty"`
EmailStatus protobuf.Email_EmailStatus `bson:"verif... |
package rpcserver
import (
"encoding/json"
"errors"
"fmt"
"github.com/incognitochain/incognito-chain/common"
"github.com/incognitochain/incognito-chain/common/base58"
"github.com/incognitochain/incognito-chain/dataaccessobject/statedb"
"github.com/incognitochain/incognito-chain/metadata"
"github.com/incognitoc... |
package game
import "fmt"
type Monster struct {
Character
}
func NewRat(pos Position) *Monster {
return &Monster{Character{
Entity: Entity{
Position: pos,
Name: "Rat",
Rune: 'R',
},
Hitpoints: 500,
Strength: 0,
Speed: 1.5,
ActionPoints: 0.0,
}}
}
func NewSpider(pos Posi... |
package metadata_test
import (
"fmt"
"testing"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/provenance-io/provenance/app"
simapp "github.com/provenance-io/provenance/app"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/typ... |
package stack
type Stack struct {
size int //栈的大小
top int //栈顶
data []int //使用切片创建栈,假使存的数据类型为int型
}
//分配一个新的栈
func CreatStack(size int) Stack {
newStack := Stack{}
newStack.size = size
newStack.data = make([]int,size)
return newStack
}
//入栈
func (s Stack) Push(data int) bool {
if(s.top ... |
package main
import (
"fmt"
"strconv"
)
func main(){
var decimal int64
fmt.Println("Enter decimal number")
fmt.Scanln(decimal)
output := strconv.FormatInt(decimal, 2)
fmt.Println("Output ", output)
} |
package main
import (
"mime/multipart"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/elitah/utils/aes"
"github.com/elitah/utils/atomic"
"github.com/elitah/utils/bufferpool"
"github.com/elitah/utils/cpu"
"github.com/elitah/utils/exepath"
"github.com/elitah/utils/hash"
"github.... |
package store
import (
"strconv"
"time"
"github.com/go-redis/redis"
"github.com/mcculleydj/currency-trader/exchange/pkg/common"
)
var client *redis.Client
// RedisConnect provides an interface to Redis
func RedisConnect() error {
client = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
_, err :=... |
package sfen
import (
"context"
"fmt"
"io"
"sort"
"strings"
)
type Surface struct {
phase Player
board [9][9]*Piece
captured []*Piece
nextStep int
}
func NewSurfaceEmpty() *Surface {
return &Surface{
phase: Player_BLACK,
nextStep: 1,
}
}
func NewSurface(pos string) (*Surface, error) {
var s... |
package analysis
import (
"fmt"
"go/token"
"go/types"
"log"
"regexp"
"strconv"
"strings"
"sync"
"github.com/frk/gosql/internal/config"
"github.com/frk/gosql/internal/typesutil"
"github.com/frk/tagutil"
)
var _ = log.Println
var _ = fmt.Println
var (
// NOTE(mkopriva): Identifiers MUST begin with a lette... |
package repository
import (
"HumoAcademy/models"
"fmt"
"github.com/jmoiron/sqlx"
)
type MainPagePostgres struct {
db *sqlx.DB
}
func NewMainPagePostgres(db *sqlx.DB) *MainPagePostgres {
return &MainPagePostgres{db: db}
}
func (r *MainPagePostgres) GetAll() (models.MainPageContent, error) {
var Content models.... |
package main
import "fmt"
/*
+ slice tham chiếu đến 1 mảng, mô tả 1 phần hoặc toàn bộ mảng
+ slice có kích thước động nên ko phải khai báo size khi khởi tạo
*/
func main() {
// khai báo silce
var slice []int
fmt.Println(slice)
//khai bao va khoi tao
var slice1 = []int{1, 2, 3, 4}
fmt.Println(slice1)
// tha... |
package libp2pquic
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"sync"
ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr"
ic "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-l... |
package business
import (
"gitlab.wallstcn.com/matrix/xgbkb/types"
)
var createProductStmt = "CREATE (p:Product {name: $name, imgActivated: $imgActivated, imgNormal: $imgNormal}) RETURN p"
func CreateProduct(productIn *types.ProductIn) (interface{}, error) {
paramsMap := make(map[string]interface{})
paramsMap["na... |
package main
import "fmt"
// 接口,定义一个能叫的类型
type speaker interface {
speak() //只要实现了speak方法的变量都是speaker类型
}
type cat struct{}
type dog struct{}
type person struct{}
func (c cat) speak() {
fmt.Printf("喵喵喵\n")
}
func (d dog) speak() {
fmt.Printf("汪汪汪\n")
}
func (p person) speak() {
fmt.Printf("啊啊啊\n")
}
func d... |
/*
Copyright © 2020 Denis Rendler <connect@rendler.me>
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... |
package main
import (
"encoding/json"
"fmt"
"os"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
"goji.io"
"goji.io/pat"
"golang.org/x/net/context"
"strings"
)
var db *sql.DB
func getSongInfoBySongName(ctx context.Context, w http.ResponseWriter, r *http.Request) {
//connecting to database
... |
package main
import "fmt"
type Vertex struct {
X int
Y int
}
/*
Struct literals - all the different ways to construct structs
*/
var (
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 30} // Y : 0 is implicit
v3 = Vertex{} // X : 0 and Y : 0 are implicit
p = &Vertex{4, 5} // has type *Vertex
)
func main() {... |
package erratum
import "errors"
func Use(ro ResourceOpener, input string) (e error) {
var resource Resource
var err error
defer func() {
rec := recover()
if rec != nil {
if errorType, isFrobError := rec.(FrobError); isFrobError {
resource.Defrob(errorType.defrobTag)
}
resource.Close()
e = erro... |
package main
import "fmt"
func main() {
// `type` is for aliases type of data's
// poc here, example below
// type byte = uint8
// type rune = int32
// type uint = uint
type cek bool
var adalahBenar cek = true
// type salah false
if adalahBenar {
fmt.Println("benar")
}
type married = bool
isMarried :=... |
package main
import (
"fmt"
"reflect"
"strings"
)
type Foo struct {
A int
B string
}
func main() {
sl := []int{1, 2, 3}
greeting := "hello"
greetingPtr := &greeting
f := Foo{A: 10, B: "Salutations"}
fp := &f
slType := reflect.TypeOf(sl)
gType := reflect.TypeOf(greeting)
grpType := reflect.TypeOf(greeti... |
package main
import (
"github.com/cemalkilic/jsonServer/config"
"github.com/cemalkilic/jsonServer/controllers"
"github.com/cemalkilic/jsonServer/database"
"github.com/cemalkilic/jsonServer/middlewares"
"github.com/cemalkilic/jsonServer/service"
"github.com/cemalkilic/jsonServer/utils/validator"... |
/*
* @lc app=leetcode.cn id=1387 lang=golang
*
* [1387] 将整数按权重排序
*/
package main
import (
"sort"
)
// @lc code=start
type Weight struct {
Val int
Step int
}
var stepMap = map[int]int{
0: 1,
1: 0,
2: 1,
}
func caculateStep(val int) int {
if step, ok := stepMap[val]; ok {
return step
} else {
if val... |
package main
import (
"errors"
"fmt"
"log"
"math"
)
// ErrNorgateMath - this is idiomatic to have error variables start with err.
// We are using Err because we want it to be accessible outside the package
var ErrNorgateMath = errors.New("norgate math: square root of negative number")
func main() {
fmt.Printf("... |
package routers
import (
"beego-blog/controllers"
"beego-blog/controllers/admin"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/", &controllers.MainController{})
ns :=
beego.NewNamespace("/admin",
beego.NSRouter("/", &admin.IndexController{}, "get:Index"),
beego.NSRouter("/login", &admin.... |
package controllers
import "github.com/superbet-group/code-cadets-2021/homework_4/03_bet_acceptance_api/internal/api/controllers/models"
type BetValidator interface {
BetIsValid(betDto models.BetDto) bool
}
|
package validations
import (
"testing"
"github.com/andrewesteves/taskee-api/entities"
)
func TestProjectFields(t *testing.T) {
project := entities.Project{
Description: "Awesome project",
}
actual := len(ProjectStore(project))
expected := 0
if actual != expected {
t.Errorf("actual: %d, expected: %d", ac... |
package main
/*
* @lc app=leetcode id=105 lang=golang
*
* [105] Construct Binary Tree from Preorder and Inorder Traversal
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(preorder []int, inorder... |
package mcservice
import (
"log"
)
func (s *MCService) liststreamkeyitems(req *JSONRequest) (*JSONResponse, error) {
if len(req.Params) < 2 {
return nil, errNumParameter
}
_, ok := req.Params[0].(string)
if ok != true {
return nil, errParameter
}
_, ok = req.Params[1].(string)
if ok != true {
return nil... |
package main
import (
"log"
"strconv"
)
type SiteConfig struct {
BlogName string
BlogDescription string
URLFormat string
PostxPage int
}
func InitConfig() {
type Option struct {
OptionName string
OptionValue string
}
var options []*Option
dbrSess := connection.NewSession(nil)
_, ... |
package pathfileops
import (
"errors"
"fmt"
"os"
"sort"
"strings"
)
// SortFileMgrByAbsPathCaseSensitive - Sorts an array of File Managers
// (FileMgr) by absolute path, filename and file extension. This sorting
// operation is performed as a 'Case Sensitive' sort meaning the upper
// and lower case charact... |
package main
import (
"fmt"
"github.com/codegangsta/cli"
)
func buildListCommand(stageList *StageList) cli.Command {
return cli.Command{
Name: "list",
Usage: "List available stages",
Action: func(c *cli.Context) {
fmt.Printf("Basic stages:\n")
for _, stageName := range stageList.S... |
package srv
import (
"context"
"log"
"net/http"
"github.com/bcspragu/Radiotation/db"
oidc "github.com/coreos/go-oidc"
)
func (s *Srv) serveVerifyToken(w http.ResponseWriter, r *http.Request) {
token := r.PostFormValue("token")
ti, err := s.verifyIdToken(token)
if err != nil {
log.Printf("verifyIdToken(%s):... |
package main
import (
"context"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-chi/chi"
"github.com/lestrrat-go/server-starter/listener"
"golang.org/x/sync/errgroup"
)
//go:generate wire ./...
func NewListener() (net.Listener, error) {
return net.Listen("tcp", "127.0.0.1:8080")
... |
package leetcode
import "testing"
func TestToGoatLatin(t *testing.T) {
if toGoatLatin("I speak Goat Latin") != "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" {
t.Fatal()
}
}
|
/*
* @lc app=leetcode.cn id=84 lang=golang
*
* [84] 柱状图中最大的矩形
*/
package main
import "fmt"
// @lc code=start
func max(a, b int) int {
if a > b {
return a
}
return b
}
/*
单调栈
func largestRectangleArea(heights []int) int {
var cur,curHeight, left, right, curWidth, ans int
newHeights := make([]int, len(heigh... |
package usecase
import (
"github.com/taniwhy/mochi-match-rest/domain/models"
"github.com/taniwhy/mochi-match-rest/domain/repository"
)
// RoomReservationUseCase :
type RoomReservationUseCase interface {
FindAllRoomReservation() ([]*models.RoomReservation, error)
FindRoomReservationByID(id int64) (*models.RoomRese... |
package ksqlclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"ksql_operator/ksqlclient/swagger"
"net/http"
"net/url"
"path"
)
type CommandStatus string
const (
ContentType = "application/vnd.ksql.v1+json"
ErrUnexpected = Error("Unexpected response")
ErrCodeNotFound = 40001... |
package page
// 4096 bits
// 24 bits meta-data header
// slots and tuples
import (
"errors"
"fmt"
//"github.com/chaitya62/noobdb/type"
)
const TABLE_NAME_LIMT = 2048
const COLUMN_NAME_LIMT = 2048
const SLOT_OFFSET = 24
const SLOT_ID_SIZE = 4
const TUPLE_LOCATION_SIZE = 2
const SLOT_SIZE = 6
type SchemaPage struc... |
package github
import (
"context"
"encoding/csv"
"fmt"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/google/go-github/v28/github"
"golang.org/x/oauth2"
)
type issueData struct {
org, repo string
number int
opened, closed bool
comments int
isPR bool
}
func IssuesAndPR... |
package nes
import (
"encoding/binary"
"errors"
"io"
"os"
)
const iNESFileMagic = 0x1a53454e
type iNESFileHeader struct {
Magic uint32 // iNES magic number
NumPRG byte // number of PRG-ROM banks (16KB each)
NumCHR byte // number of CHR-ROM banks (8KB each)
Control1 byte // control bits
Cont... |
package main
import (
"database/sql"
"fmt"
"librarymanager/users/common"
"librarymanager/users/controllers"
"librarymanager/users/domain"
"librarymanager/users/services"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
_ "github.com/mattn/go-sqlite3"
)
func main() {
fmt.Println("Users process")
... |
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"task/defs"
"task/utils"
"time"
)
var (
help bool
env string //"env6"
podBaseDir string // "/mnt/paas/kubernetes/kubelet/pods/"
backupDestBaseDir string // "/tmp/pods/"
restApiUrl string // "http://192.168.250.22:32598"
expired int... |
// Copyright 2019 Radiation Detection and Imaging (RDI), LLC
// Use of this source code is governed by the BSD 3-clause
// license that can be found in the LICENSE file.
package data
import (
"math"
"github.com/rditech/rdi-live/model/rdi/currentmode"
"github.com/proio-org/go-proio"
)
type Pedestals struct {
Al... |
package fateRPGtest
import (
"testing"
"github.com/faterpg"
)
func TestNewPlayer(t *testing.T) {
player := faterpg.NewGM()
if player == nil {
t.Error("NewPlayer retrun nil")
}
}
func TestPlayerAttr(t *testing.T) {
player := faterpg.NewPlayer()
player.Name = "Test name"
pc := faterpg.NewPC()
player.PC = p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.