text stringlengths 11 4.05M |
|---|
package engine
import (
"github.com/stretchr/testify/assert"
"github.com/zhenghaoz/gorse/core"
"os"
"path"
"testing"
)
func TestDB_InsertGetFeedback(t *testing.T) {
// Create database
db, err := Open(path.Join(core.TempDir, "/test_feedback.db"))
if err != nil {
t.Fatal(err)
}
// Insert feedback
users := ... |
/*
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... |
// Copyright (C) 2019 Cisco Systems 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 agr... |
package main
import (
"Lab1/internal/pgk/Person/Delivery"
"Lab1/internal/pgk/Person/Repository"
"Lab1/internal/pgk/Person/Usecase"
"Lab1/internal/pgk/middleware"
"context"
"github.com/gorilla/mux"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/joho/godotenv"
"log"
"net/http"
"os"
"time"
)
func init() {
if... |
// ˅
package main
// ˄
type IData interface {
Item
Add(item Item)
// ˅
// ˄
}
// ˅
// ˄
|
package resolver
import (
"context"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
type Probe struct {
addr string
conn *grpc.ClientConn
ctx context.Context
cancel context.CancelFunc
}
func newProbe(addr string, timeout time.Duration) (*Probe, error) {
ctx, cancel := context... |
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/osbuild/osbuild-composer/internal/common"
"github.com/osbuild/osbuild-composer/internal/upload/azure"
"github.com/osbuild/osbuild-co... |
package tstune
import (
"bytes"
"fmt"
"io"
"os"
"strings"
"testing"
"github.com/timescale/timescaledb-tune/pkg/pgtune"
"github.com/timescale/timescaledb-tune/pkg/pgutils"
)
func stringSliceToBytesReader(lines []string) *bytes.Buffer {
return bytes.NewBufferString(strings.Join(lines, "\n"))
}
func TestRemov... |
package main
import "fmt"
func main() {
y := []string{"sun", "moon", "star", "rocket", "foot", "face"}
fmt.Println(y)
fmt.Println(cap(y))
fmt.Println(len(y))
for i, v := range y {
fmt.Println(i, v)
}
}
|
package ruleguard
import (
"go/ast"
"go/token"
"go/types"
"io"
)
type Context struct {
Types *types.Info
Fset *token.FileSet
Report func(n ast.Node, msg string)
}
func ParseRules(filename string, fset *token.FileSet, r io.Reader) (*GoRuleSet, error) {
p := newRulesParser()
return p.ParseFile(filename, fs... |
// 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 download
// Data struct for download options.
type Options struct {
Destination string
}
// Set the destination
func (options Options) SetDestination(destination string) {
options.Destination = destination
} |
package make_tree
import "io"
// Actions are the callbacks to use to
// make a particular filesystem tree.
type Action interface {
// Executes the direct action. It must
// return an error on failure.
Do(currentDirectory string, dump io.Writer, logRan func(string, Action)) error
// Executes the inverse action. It... |
package mongo
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Connect is a wrapped function to the original mongo.Connect for avoiding package name conflict
func Connect(ctx context.Context, opts ...*options.ClientOptions) (*mongo.Client, error) {
return mon... |
package main
import (
"github.com/nsf/termbox-go"
)
type Commander struct {
}
func (self *Commander) Draw(w, h int) {
for i := 1; i < w; i++ {
termbox.SetCell(i, h-2, '─', 0x31, 0x00)
}
}
|
package modules
import "fmt"
type Executor interface {
fmt.Stringer
Execute([]string) error
}
var SupportedModules = map[string]func() Executor{
"backend": NewBackendModule,
}
func ModuleFactory(module string) (Executor, error) {
if moduleInitFunc, ok := SupportedModules[module]; !ok {
return nil, fmt.Errorf(... |
package parsing_test
import (
"testing"
. "github.com/s2gatev/sqlmorph/ast"
)
func TestSelectParsing(t *testing.T) {
runSuccessTests(t, []successTest{
{
Query: `SELECT Name FROM User`,
Expected: &Select{
Fields: []*Field{
&Field{Name: "Name"},
},
Table: &Table{Name: "User"},
},
},
... |
// https://eli.thegreenplace.net/2020/pubsub-using-channels-in-go/
package main
import (
"fmt"
"sync"
)
type Pubsub struct {
mu sync.RWMutex
subs map[string][]chan string
closed bool
}
func NewPubsub() *Pubsub {
ps := &Pubsub{}
ps.subs = make(map[string][]chan string)
return ps
}
func (ps *Pubsub) Sub... |
package model
import (
"github.com/feast-dev/feast/go/protos/feast/core"
)
type FeatureViewProjection struct {
Name string
NameAlias string
Features []*Field
JoinKeyMap map[string]string
}
func (fv *FeatureViewProjection) NameToUse() string {
if len(fv.NameAlias) == 0 {
return fv.Name
}
return fv.... |
// Package russian implements functions to manipulate russian words.
package russian
import (
"fmt"
"github.com/POSOlSoft/go/mathhelper"
)
// GrammaticalGender - russian grammatical gender.
type GrammaticalGender int
const (
// Neuter - средний род.
Neuter = iota
// Masculine - мужской род.
Masculine
// Femi... |
package core
import (
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/textileio/go-textile/pb"
)
// lsThreadFeed godoc
// @Summary Paginates post and annotation block types
// @Description Paginates post (join|leave|files|message) and annotation (comment|like) block types
// @Description T... |
package utils
import (
"strings"
"github.com/gosimple/slug"
"encoding/base64"
)
func Slugify(raw string) string {
s := slug.Make(strings.ToLower(raw))
if s == "" {
// If the raw name is only characters outside of the
// sluggable characters, the slug creation will return an
// empty string which will mess ... |
package main
// Display a character string with a decorative frame.
func main() {
displayA := NewMessageDisplay("Nice to meet you.")
displayA.Show(displayA)
displayB := NewSideFrame(displayA, "!")
displayB.Show(displayB)
displayC := NewFullFrame(displayB)
displayC.Show(displayC)
displayD := NewSideFrame(
... |
package shortenertest
import (
"testing"
"github.com/go-playground/validator"
"github.com/toms1441/urlsh/internal/shortener"
)
var invalidconfig = [3]shortener.Config{
{},
{Length: 1},
{Characters: "1"},
}
var validconfig = shortener.Config{
Length: 4,
Characters: "abcdef",
}
var validate *validator.Va... |
package main
import (
"bufio"
"fmt"
"strings"
"os"
"strconv"
)
func sliceAtoi(sa []string) ([]int, error) {
si := make([]int, 0, len(sa))
for _, a := range sa {
i, err := strconv.Atoi(a)
if err != nil {
return si, err
}
si = append(si, i)
}
return si, n... |
package main
import(
"fmt"
"os"
"net"
)
//Function main uses localhost port 1300 to listen and accpet connections
//uses a go routine to handle client connections
func main() {
address := "127.0.0.1:1300"
tcpAddr, err := net.ResolveTCPAddr("tcp4", address)
checkError(err)
listener, err := net.ListenT... |
package app
import "github.com/bryanl/dolb/entity"
// AgentBuilder creates and configures agents.
type AgentBuilder interface {
Create(id int) (*entity.Agent, error)
Configure(agent *entity.Agent) error
}
|
package problem0315
func countSmaller(nums []int) []int {
count := make([]int, len(nums))
indexes := make([]int, len(nums))
for i := range nums {
indexes[i] = i
}
mergeSort(nums, &count, &indexes, 0, len(nums)-1)
return count
}
func mergeSort(nums []int, count, indexes *[]int, left, right int) {
if left >= r... |
package cron
import (
"errors"
"github.com/spf13/cobra"
"github.com/wish/ctl/cmd/util/parsing"
"github.com/wish/ctl/pkg/client"
)
func unsuspendCmd(c *client.Client) *cobra.Command {
return &cobra.Command{
Use: "unsuspend cronjob [flags]",
Short: "Unsuspend a cron job",
Long: `Unsuspends the specified cr... |
package storage
import (
"io"
"os"
"github.com/mlmhl/gcrawler/types"
)
const fileStorageName = "File"
var _ Storage = FileStorage{}
// FileStorage write all Item to a file on local disk.
type FileStorage struct {
file *os.File
}
func NewFileStorage(path string) (FileStorage, error) {
file, err := os.OpenFile... |
/*
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 main
import (
"fmt"
"log"
"os"
"github.com/square/p2/pkg/kp"
"github.com/square/p2/pkg/kp/flags"
"github.com/square/p2/Godeps/_workspace/src/gopkg.in/alecthomas/kingpin.v2"
"github.com/square/p2/pkg/version"
)
var (
nodeName = kingpin.Flag("node", "The node to do the scheduling on. Uses the host... |
// 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 discover
import (
"github.com/reed/common/byteutil/byteconv"
"github.com/reed/log"
"github.com/sirupsen/logrus"
"math/rand"
"sor... |
package chanqueue
import (
"sync"
)
type CQueue struct {
sync.RWMutex
data []struct{} // Size should remain constant throughout.
out int // Where to pop.
in int // Where to push.
done bool
}
func NewCQueue() *CQueue {
return &CQueue{
data: make([]struct{}, 1000),
}
}
// Done marks queue a... |
package main
import "fmt"
func main() {
// 1、以下代码正确的输出是什么?
var fn1 = func() {
}
var fn2 = func() {
}
// if fn1 != fn2 {
// println("fn1 not equal fn2")
// }
// 答案: 编译错误, 函数不能比较, 函数只能与nil比较
if fn1 != nil {
println("fn1 not equal nil")
}
if fn2 != nil {
println("fn2 not equal nil")
}
// 以上两个可以正... |
package main
import (
"bytes"
"encoding/hex"
"log"
"github.com/syndtr/goleveldb/leveldb"
)
//Blockchain Variable
const (
BlockChainLast = "tip"
BlockchainFile = "lubit.db.block"
)
// BlockChain struct
type BlockChain struct {
tip []byte
lvl *leveldb.DB
}
// NewBlockChain return a new block chain
func NewBl... |
package main
import (
"flag"
"io"
_ "github.com/go-sql-driver/mysql"
"net/http"
)
func silentHandle(w http.ResponseWriter, req *http.Request) {
liveid := req.FormValue("liveid")
userid := req.FormValue("userid")
if len(liveid) < 6 {
if len(userid) < 3 {
io.WriteString(w, "parameter... |
package languages
const (
// LanguagesGetLanguages is a string representation of the current endpoint for getting languages
LanguagesGetLanguages = "v1/metadata/getLanguages"
)
// Language is a struct containing matching data for a language found in text
type Language struct {
// Name - the language identified
Na... |
package main
import (
"code.google.com/p/go.net/websocket"
"log"
)
type Msg struct {
Route string `json:"route"`
Data map[string]string `json:"data"`
}
func (m *Msg) Send(ws *websocket.Conn) {
if err := websocket.JSON.Send(ws, &m); err != nil {
log.Println("send err", err)
}
}
|
package main
import (
"fmt"
"github.com/sunmi-OS/gocore/utils"
)
func main() {
var urls string
urls = "https://www.sunmi.com/"
e, err := utils.UrlEncode(urls)
if err != nil {
fmt.Println("UrlEncode failed error", err)
}
fmt.Println("UrlEncode", e)
r, err := utils.UrlDecode(urls)
if err != nil {
fmt.... |
package commands
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"fmt"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/authelia/authelia/v4/internal/utils"
)
func newCryptoCmd(ctx *CmdCtx) (cmd *cobra.Command) {
cmd = &cobra.Command{
Use: cmdUseCrypto,
Short: cmdAutheli... |
package gui
import "tetra/lib/glman"
// TestPane is a pane for testing
type TestPane struct {
Pane
btn IButton
}
// Init a new object
func (pn *TestPane) Init() {
pn.btn = NewButton()
pn.btn.SetFont(glman.LoadFont("WQY-ZenHei", 20))
pn.Insert(-1, pn.btn)
}
// State to string
func (pn *TestPane) State() ([]byte... |
package hot100
// 关键:
// 判断是否需要额外加一即可
func plusOne(digits []int) []int {
if len(digits) == 0 {
return nil
}
for i := len(digits) - 1; i >= 0; i-- {
digits[i]++
digits[i] %= 10
if digits[i]!=0{
return digits
}
}
// 当运行到这里的时候,表明之前的数字都是 99999
ret:=make([]int, len(digits)+1)
ret[0]=1
return ret
}
|
package storage
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
type S3Storage struct {
Bucket string
}
func NewS3Storage(bucket string) S3Storage {
return S3Storage{
Bucket: bucket,
... |
package main
import (
"github.com/micro/go-micro/client"
"github.com/plexmediamanager/micro-redis/proto"
"github.com/plexmediamanager/micro-redis/redis"
"github.com/plexmediamanager/micro-redis/resolver"
"github.com/plexmediamanager/service"
"github.com/plexmediamanager/service/log"
"time"
... |
package cmd_test
import (
"testing"
"opendev.org/airship/airshipctl/cmd"
"opendev.org/airship/airshipctl/testutil"
)
func TestVersion(t *testing.T) {
versionCmd := cmd.NewVersionCommand()
cmdTests := []*testutil.CmdTest{
{
Name: "version",
CmdLine: "",
Cmd: versionCmd,
},
{
Name: "ve... |
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/etcd-io/etcd/clientv3"
"github.com/gin-gonic/gin"
)
type node struct {
Id string `json:"node_id"`
TcpAddr string `json:"tcp_addr"`
HttpAddr string `json:"h... |
package main
import (
"encoding/json"
"errors"
"strings"
"time"
"bytes"
"fmt"
"os/exec"
"github.com/k0kubun/pp"
log "github.com/sirupsen/logrus"
)
func FindCommandPath(name string, env []string) (bool, string) {
cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("command -v %s", name))
cmd.Env = env
stdo... |
package counter
import (
"sync"
"time"
)
type bucket struct {
val int64
next *bucket
}
func (b *bucket) Add(val int64) {
b.val += val
}
func (b *bucket) Value() int64 {
return b.val
}
func (b *bucket) Reset() {
b.val = 0
}
var _ Counter = new(rollingCounter)
type rollingCounter struct {
mu sync.... |
package database
import (
"database/sql"
"gotodo/database/todos"
)
// Database defines our database struct.
type Database struct {
Todos *todos.Database
}
// New returns as new gotodo database.
// able to pass down the database in todos folder
func New(db *sql.DB) *Database {
return &Database{
Todos: todos.Ne... |
package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
)
var success = 0
type LoginController struct {
beego.Controller
}
func (c *LoginController) Get() {
c.TplName = "login.html"
c.Data["IsSuccess"] = success == 1
c.Data["IsFailed"] = success == 2
}
func (c *LoginControl... |
package jarviscore
import (
"context"
// "encoding/json"
"net/http"
"time"
// "github.com/zhs007/dtdataserv/proto"
// "github.com/zhs007/jarviscore/base"
// "go.uber.org/zap"
)
// func replyDTReport(w http.ResponseWriter, report *dtdatapb.DTReport) {
// jsonBytes, err := json.Marshal(report)
// if err != nil... |
package main
import (
"fmt"
"net/http"
"net"
)
func getIP(w http.ResponseWriter, req *http.Request) string {
returnValue := "window.ipaddr="
ip, port, err := net.SplitHostPort(req.RemoteAddr)
_ = port
if err == nil {
userIP := net.ParseIP(ip)
if userIP == nil {
return returnValue + "'';"
}
forward :... |
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package privet
type (
_SpecialTranslationClass string
)
//goland:noinspection GoSnakeCaseUsage
const (
__SPTR_PREFIX = _SpecialTranslationCla... |
package fasdas
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func Zadanie4() {
a := zapola()
fmt.Println(a)
}
func zapola() string {
text := getInputText()
s := strings.Split(text, "")
naoborot(s)
return strings.Join(s, "")
}
func getInputText() string {
scanner := bufio.NewScanner(bufio.NewReader(os... |
package main
import "fmt"
func main() {
c := make(chan int)
go func() {
for i := 0; i < 10; i++ {
c <- i
}
// close(c)
}()
fmt.Println(<-c)
// // My solution :
// for i := 0; i < 10; i++ {
// fmt.Println(<-c)
// }
}
// Why does this only print zero?
// And what can you do to get it to print all... |
package unionfind
import (
"fmt"
"testing"
)
func TestNewUnionFind3(t *testing.T) {
fmt.Println("============UF3==========")
uf := NewUnionFind3(5)
fmt.Println("uf:", uf)
fmt.Println("1的parent:", uf.Find(1))
fmt.Println("0和3的连接关系:", uf.IsConnected(0, 3))
fmt.Println("0和3连接中...")
uf.Union(0, 3)
fmt.Println("... |
package daemons
import (
"encoding/binary"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"docktor/server/storage"
"docktor/server/types"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
"golang.org/x/net/websocket"
)
// getContainers get containers from daemon
func getContainers(c echo.Context)... |
package xdominion
/*
The XGroup is an array of XGroupBy structures
*/
type XGroup []XGroupBy
func (g *XGroup) CreateGroup(table *XTable, DB string) string {
group := ""
for _, xg := range *g {
group += xg.GetGroup(table, DB)
}
return group
}
/*
The XGroupBy structure
*/
type XGroupBy struct {
Field str... |
package proxy
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"reflect"
"regexp"
"strings"
"time"
"github.com/buzzfeed/sso/internal/pkg/aead"
log "github.com/buzzfeed/sso/internal/pkg/logging"
"github.com/buzzfeed/sso/internal/proxy/collector... |
package rtda
import "jvmgo_c/ch11/rtda/heap"
func NewShimFrame(thread *Thread,ops *OperandStack) *Frame {
return &Frame{
thread: thread,
method: heap.ShimReturnMethod(),
operandStack:ops,
}
}
|
package controller
import (
"github.com/fberrez/forum/model"
"github.com/gin-gonic/gin"
"log"
"net/http"
"strconv"
)
func GetCategory(c *gin.Context) {
categories, err := model.GetCategory()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"executed": false, "message": err})
log.Fatalf("getCat... |
package server
import (
"log"
"github.com/cswank/quimby/internal/auth"
"github.com/cswank/quimby/internal/config"
"github.com/cswank/quimby/internal/homekit"
"github.com/cswank/quimby/internal/repository"
"github.com/cswank/quimby/internal/router"
"github.com/cswank/quimby/internal/templates"
)
func Start(cfg... |
// Package main contains pomerium
package main
import (
"context"
"errors"
"flag"
"fmt"
"github.com/rs/zerolog"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/version"
"github.com/pomerium/pomerium/pkg/cmd/pomerium"
"github.com/pomer... |
package main
import (
"fmt"
"net/url"
"time"
"github.com/kavenegar/kavenegar-go"
)
func main() {
api := kavenegar.New(" your apikey ")
//Message.Send
sender := "" //Sender Line Number(optional)
receptor := []string{"", ""} //Recipient numbers
message := "Hello Go!" //Text message
par... |
// 15 april 2015
package pgidl
import (
"io"
"text/scanner"
"strconv"
)
type lexerr struct {
msg string
pos scanner.Position
}
type lexer struct {
scanner *scanner.Scanner
idl IDL
errs []lexerr
}
func newLexer(r io.Reader, filename string) *lexer {
l := new(lexer)
l.scanner = new(scanner.Scanner)
l.s... |
package events
import (
"encoding/json"
"errors"
"fmt"
)
// Event is an immutable event to be handled
type Event struct {
typeField uint
completed bool
err error
Payload interface{}
}
// NewEvent constructs an event of the given type and optional payload
func NewEvent(typeValue uint, payload ...interf... |
package starportcmd
import (
"fmt"
"github.com/tendermint/starport/starport/pkg/chaincmd"
"github.com/spf13/cobra"
"github.com/tendermint/starport/starport/services/chain"
)
// NewRelayer creates a new command called chain that holds IBC Relayer related
// sub commands.
func NewRelayer() *cobra.Command {
c := ... |
package main
import (
"github.com/astaxie/beego"
)
type MainController struct {
beego.Controller
}
type DelController struct {
beego.Controller
}
type ViewController struct {
beego.Controller
}
func (this *ViewController) Get() {
this.Ctx.SetCookie("age","",-1)
this.Ctx.WriteString("view wor... |
package geoip2
import (
"fmt"
"log"
"net"
"os"
"path/filepath"
"strings"
"sync"
"github.com/abh/geodns/countries"
"github.com/abh/geodns/targeting/geo"
geoip2 "github.com/oschwald/geoip2-golang"
)
type geoType uint8
const (
countryDB = iota
cityDB
asnDB
)
var dbFiles map[geoType][]string
// GeoIP2 co... |
package room
import (
"fmt"
"github.com/mooncaker816/gophercises/poker/deck"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
)
type Table struct {
result *sdl.Texture
Players []*Player
Deck *deck.Deck
}
// AddDeck create new deck as desired
func (t *Table) AddDeck(n int) deck.Deck {
d ... |
package twch
import (
"fmt"
"net/http"
"reflect"
"testing"
)
func TestListEmoticons(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/chat/emoticons", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{ "_links": { "self": "s" }, "emoticons": [ { "r... |
// compact.
package main
import (
"bytes"
"encoding/json"
"fmt"
)
var j = []byte(`[
{
"name": "lily",
"age": 11
},
{
"name": "dory",
"age": 12
}
]`)
func main() {
b := new(bytes.Buffer)
err := json.Compact(b, j)
if err != nil {
panic(err)
}
fmt.Printf("json.Compact:\n")
fmt.Printf("Before:%s\... |
package main
import "fmt"
var globalVar = "This is a global variable and can be used in any function"
func main(){
var x string = "Hello, World"
var b bool
fmt.Println(x)
boo()
b = tonto()
fmt.Println("The value received by tonto is:", b)
fmt.Printf("The value received by tonto is: %t \n", b)
cadenas("uno",... |
package humanity
import "fmt"
type Preparer interface {
Prepare() error
}
func (h *Human) Prepare() error {
if h.Ready == true {
fmt.Printf("%v is ready !\n", h)
}
h.Ready = true
return nil
}
func PrepareMissionPart(objs ...Preparer) error {
for i := range objs {
Preparer.Prepare(objs[i])
}
return nil
}... |
package aes
import (
"testing"
"github.com/iGoogle-ink/gotil/xlog"
)
var (
secretKey = "GYBh3Rmey7nNzR/NpV0vAw=="
iv = "JR3unO2glQuMhUx3"
)
func TestDesCBCEncryptDecrypt(t *testing.T) {
originData := "www.gopay.ink"
xlog.Debug("originData:", originData)
encryptData, err := DesCBCEncryptData([]byte(ori... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-07-21 09:41
# @File : _206_Reverse_Linked_List.go
# @Description : 反转链表,涉及到头结点,所以需要引入dummyNode
# @Attention :
返回值,因为是反转,所以需要返回的是prev的值
*/
package v0
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
var temp *ListNode
for nil != head {
t... |
package util
import (
"github.com/umeat/go-gnss/cmd/database/models"
"github.com/geoscienceaustralia/go-rtcm/rtcm3"
)
func ParseSatelliteMask(satMask uint64) (prns []int) {
for i, prn := 64, 1; i > 0; i-- {
if (satMask >> uint64(i-1)) & 0x1 == 1 {
prns = append(prns, prn)
}
prn++
}
return prns
}
func P... |
package main
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestJsonResponseString(t *testing.T) {
j := jsonResponse{"a": "b"}
expected := `{
"a": "b"
}`
if j.String() != expected {
t.Errorf("Expected: %v, Received: %v", expected, j.String())
}
}
func TestGetIPAddress(t *testing.T) ... |
// test-sort1 project doc.go
/*
test-sort1 document
*/
package main
|
package semt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document02200101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:semt.022.001.01 Document"`
Message *SecuritiesSettlementTransactionAuditTrailReportV01 `xm... |
package atomix
import (
"strconv"
"sync/atomic"
)
// AlignedInt64 is an atomic wrapper around an int64 aligned to a cache line.
type AlignedInt64 struct {
atomicType
value int64
_ [CacheLine - 8]byte // unsafe.Sizeof(int64) == 8
}
// NewAlignedInt64 creates an AlignedInt64.
func NewAlignedInt64(i int64) *Al... |
package basic
import "fmt"
func RangeSliceMap() {
a := []int{10, 20, 30}
for n := range a {
fmt.Println( n)
}
for k, v := range a {
fmt.Println(k, v)
}
b := map[string]int{"top1": 1000, "top2": 500}
for k, v := range b {
fmt.Println(k, v)
}
}
func RangeByte1() {
data := "A\xfe\x02\xff\x04"
for _, ... |
package philifence
import (
"encoding/json"
"github.com/julienschmidt/httprouter"
"io"
"io/ioutil"
"net/http"
"net/http/pprof"
"strconv"
)
var fences, roads FenceIndex
func ListenAndServe(addr string, fidx, ridx FenceIndex, profile bool) error {
info("Listening on %s\n", addr)
defer info("Done Fencing\n")
... |
// imgListDownLoad
package DaeseongLib
import (
"fmt"
_ "io"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
)
var (
IMGS []string
)
func downloadbytes(sUrl string) ([]byte, error) {
req, err := http.NewRequest("GET", sUrl, nil)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", "Daeseongli... |
package easy349
func intersection(nums1 []int, nums2 []int) []int {
set := make(map[int]struct{})
for _, v := range nums1 {
set[v] = struct{}{}
}
ansSet := make(map[int]struct{})
for _, v := range nums2 {
_, ok := set[v]
if ok {
ansSet[v] = struct{}{}
}
}
ans := []int{}
for k := range ansSet {
a... |
package _1_Two_Sum
func twoSum(nums []int, target int) []int {
// return twoSumForce(nums, target)
return twoSumHash(nums, target)
}
func twoSumHash(nums []int, target int) []int {
var (
m = make(map[int]int)
)
for idx, n := range nums {
m[n] = idx
}
for idx1, n := range nums {
if idx2, ok := m[target-n]... |
package helpers
import "net/url"
/* IsValidUrl: checks if a url is valid
Param: toTest (string) - url to check
Returns: boolean
sample valid url: `http://www.domain-address.com`
*/
func IsValidUrl(toTest string) bool {
_, err := url.ParseRequestURI(toTest)
if err != nil {
return false
}
u, err := url.... |
package syscallx
/* This is the source file for msync_*.go, to regenerate run
./generate
*/
//sys Msync(b []byte, flags int) (err error)
|
package query
import (
"fmt"
"sort"
"core"
)
// ReverseDeps For each input label, finds all targets which depend upon it.
func ReverseDeps(graph *core.BuildGraph, labels []core.BuildLabel) {
uniqueTargets := make(map[core.BuildLabel]struct{})
for _, label := range labels {
for _, child := range graph.Packag... |
package fzb
import (
"testing"
)
func Test_Fzb(t *testing.T) {
f := NewFzb()
f.Title = "test"
fxml, err := f.ParseXML()
if err != nil {
t.Error(err)
}
t.Log(string(fxml))
}
|
package main
/*
* @lc app=leetcode id=236 lang=golang
*
* [236] Lowest Common Ancestor of a Binary Tree
*/
/**
* Definition for TreeNode.
* type TreeNode struct {
* Val int
* Left *ListNode
* Right *ListNode
* }
*/
func lowestCommonAncestor_PLEASE_REMOVE_THIS(root, p, q *TreeNod... |
package main
type Config struct {
bindAddr string `toml:"bind_addr"`
mocksFolder string `toml:"mocks_folder"`
Routes []Route `toml:"routes"`
}
type Route struct {
Path string `toml:"path"`
Filename string `toml:"filename"`
}
func NewConfig() *Config {
return &Config{
bindAddr: ":8080",
moc... |
package messagebird
import (
"testing"
"time"
)
var voiceMessageObject []byte = []byte(`{
"id":"430c44a0354aab7ac9553f7a49907463",
"href":"https:\/\/rest.messagebird.com\/voicemessages\/430c44a0354aab7ac9553f7a49907463",
"originator":"MessageBird",
"body":"Hello World",
"reference":null,
"language":"en-... |
package main
import (
"context"
"fmt"
"strconv"
"time"
"example.com/m/global"
"github.com/go-redis/cache/v8"
)
// func rClient() *redis.Client {
// client := redis.NewClient(&redis.Options{
// Addr: "localhost:6379",
// })
// return client
// }
// func ping(client *redis.Client) error {
// pong, err := c... |
package limiter
import (
"log"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/mash/go-limiter/adaptor"
)
const (
// The header name to retrieve an IP address under a proxy
forwardedForHeader = "X-FORWARDED-FOR"
)
type Quota struct {
Limit uint64
Within time.Duration
}
func (q Quota) ResetUnix(... |
package library
import (
"errors"
"fmt"
"regexp"
"sort"
"github.com/devinmcgloin/sail/pkg/sketch"
"github.com/devinmcgloin/sail/pkg/sketch/accrew"
"github.com/devinmcgloin/sail/pkg/sketch/delaunay"
"github.com/devinmcgloin/sail/pkg/sketch/gradients"
"github.com/devinmcgloin/sail/pkg/sketch/harmonograph"
"gi... |
package pointer
import (
"reflect"
"time"
)
// New converts value to pointer
func New(value interface{}) interface{} {
rv := reflect.ValueOf(value)
if rv.Type().Kind() == reflect.Ptr {
return value
}
rp := reflect.New(rv.Type())
rp.Elem().Set(rv)
return rp.Interface()
}
// String converts string to pointer... |
package web_dao
import (
"2021/yunsongcailu/yunsong_server/dial"
"2021/yunsongcailu/yunsong_server/web/web_model"
)
type ConsumerDao interface {
// 根据ID 查询用户
QueryConsumerById(id int64) (consumer web_model.Consumers,err error)
// 根据邮箱查询用户
QueryConsumerByEmail(email string) (consumer web_model.Consumers,err erro... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//331. Verify Preorder Serialization of a Binary Tree
//One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.