text stringlengths 11 4.05M |
|---|
package testcase
type Options struct{}
|
package zgok
import (
"errors"
"flag"
"fmt"
"os"
"regexp"
"strings"
"text/template"
)
type Command interface {
// Sub-command name. Name must return one word, otherwise it goes undefined.
Name() string
// Short description for this command
Desc() string
// If you want to use flags for this command, retu... |
package Problem0342
func isPowerOfFour(n int) bool {
if n < 1 {
return false
}
for n%4 == 0 {
n /= 4
}
return n == 1
}
|
package main
import (
"fmt"
)
func main() {
var i, j int
var text string
fmt.Scan(&i)
fmt.Scan(&text)
fmt.Scan(&j)
shift := j % 26
plain := []rune(text)
cipher := genCaesarCipher(shift)
var encrypted []rune
for i, a := range plain {
val, ok := cipher[a]
if ok {
encrypted = append(encrypted, val)
}... |
package auto_close_order
import (
"fmt"
"github.com/streadway/amqp"
"mall_server/internal/services"
"mall_server/store"
)
var rabbitmqService = new(store.Rabbitmq)
var orderService = new(services.OrderService)
func Do() {
ch, err := rabbitmqService.Get().Channel()
if err != nil {
panic(err)
}
defer ch.Clos... |
// hello-world is a simple web server for testing connections and configurations.
package main
import "github.com/composer22/hello-world/server"
// main is the main entry point for the application or server launch.
func main() {
server.New().Start()
}
|
package config
import (
"fmt"
"io/ioutil"
)
func ReadFileContents(fileToEncrypt string) (string, error) {
var dat, err = ioutil.ReadFile(fileToEncrypt)
if err != nil {
return "", fmt.Errorf("Error opening file at path %s : %s", fileToEncrypt, err)
}
return string(dat), nil
}
|
/*
* Lists IP addresses for a network in a given data center for a given account.
*/
package main
import (
"encoding/hex"
"flag"
"fmt"
"net"
"os"
"path"
"github.com/grrtrr/clcv2"
"github.com/grrtrr/clcv2/clcv2cli"
"github.com/grrtrr/clcv2/utils"
"github.com/grrtrr/exit"
"github.com/kr/pretty"
"github.co... |
/*
* Strava API v3
*
* The [Swagger Playground](https://developers.strava.com/playground) is the easiest way to familiarize yourself with the Strava API by submitting HTTP requests and observing the responses before you write any client code. It will show what a response will look like with different endpoints depen... |
package main
import (
"errors"
"fmt"
"log"
"github.com/boltdb/bolt"
)
func writeNBytes(bdb *bolt.DB, k []byte, N int) error {
buf := make([]byte, N)
return bdb.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("predicate"))
if err != nil {
return err
}
return bucket.P... |
package helpers
import (
"fmt"
"golang.org/x/crypto/bcrypt"
"log"
)
func GetPwd(pwd string) []byte {
_, err := fmt.Scan(pwd)
if err != nil {
log.Println(err)
}
return []byte(pwd)
}
func HashAndSalt(pwd []byte) string {
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
log.Pr... |
// Copyright 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... |
package controllers
type IndexController struct {
BaseController
}
func (this *IndexController) Index() {
this.TplName = "index.html"
}
|
package api
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jordan-wright/email"
"go.uber.org/zap"
"math/rand"
"net/http"
"net/smtp"
"shop-web/user-api/forms"
"shop-web/user-api/global"
"shop-web/user-api/utils"
"strings"
"time"
)
func GetEmail(ctx *gin.Context) {
emailForm := forms.EmailForm{}
if... |
package olm
import (
"fmt"
"strings"
"github.com/operator-framework/api/pkg/operators/v1alpha1"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/registry/resolver/cache"
opregistry "github.com/operator-framework/operator-registry/pkg/registry"
extv1 "k8s.io/apiextensions-apiserver/pkg/ap... |
package stat
import (
"testing"
"time"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/pascaldekloe/sqltest"
"gitlab.com/thorchain/midgard/internal/timeseries"
)
func init() {
sqltest.Setup("pgx", "user=midgard password=password host=localhost port=5432 sslmode=disable dbname=midgard")
}
var testWindow = Wind... |
package main
import (
"encoding/json"
"fmt"
"github.com/cnjack/throttle"
"regexp"
// "github.com/dchest/captcha"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"io"
"io/iout... |
package main
import (
"fmt"
"go/build"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
)
const (
debug = false
// Whether to redirect the go cmd's stdout and stderr to tty.
goTTY = false
execWithPidSuffix = false
)
// args should not include the executed file path co... |
package main
// config will be populated with the retrieved values from environment variables
// configured as step inputs.
type config struct {
BuildNumber string `env:"BITRISE_BUILD_NUMBER"`
AppTitle string `env:"BITRISE_APP_TITLE"`
AppURL string `env:"BITRISE_APP_URL"`
BuildURL string `env:"BITRISE_B... |
package cmd
import (
"os"
"log"
"github.com/spf13/cobra"
"github.com/corentindeboisset/golang-api/app/service"
)
// Version command
func init() {
rootCmd.AddCommand(&cobra.Command{
Use: "db:migrate",
Short: "Upgrade the database to the latest version",
Long: `Upgrade the database to the latest version`,... |
package helpers
import "strings"
func NickConvert(destination string) (string, bool) {
metaFlag := strings.HasPrefix(destination, "bnb")
if metaFlag && len(destination) == 42 {
return destination, false
}
return destination, true
}
|
// go run set.go
// https://github.com/Workiva/go-datastructures/blob/master/set/dict_test.go
package main
import (
"fmt"
"github.com/Workiva/go-datastructures/set"
)
func main() {
s := set.New()
s.Add("this")
s.Add("and")
s.Add("this")
s.Add(1)
s.Add(1)
fmt.Println(s.Len()) // 3
fmt.Println(s.Exi... |
package main
import (
"os"
"testing"
"github.com/gabrie30/ghorg/configs"
)
func TestDefaultBranch(t *testing.T) {
configs.Load()
if os.Getenv("GHORG_BRANCH") != "master" {
t.Errorf("Default branch should be master")
}
}
|
package handlers
import "github.com/gin-gonic/gin"
func Register(router *gin.Engine) {
r := router.Group("/api")
RegisterHello(r)
RegisterPay(r)
}
|
package util
type ContainerRestarter interface {
RestartContainer() error
}
|
package config
import (
"github.com/spf13/viper"
)
type (
Config struct {
ServiceName string `json:"service_name"`
Address string `json:"address"`
Tracer Tracer `json:"tracer"`
Log Log `json:"log"`
}
Tracer struct {
AgentAddress string `json:"agent_address"`
}
Log struct {
File... |
// Copyright 2015 The go-symverse Authors
// This file is part of the go-symverse library.
//
// The go-symverse library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... |
package gotafseer
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type TafseerApiClient struct {
BaseURL *url.URL
}
var (
QuranPath url.URL = url.URL{Path: "/quran"}
TafseerPath url.URL = url.URL{Path: "/tafseer"}
)
func (c *TafseerApiClient) ListChapters() ([]Chapter, error) {
var ch []Chapter
r :... |
package handler
import (
"testing"
)
func TestSanitizeStartCommand(t *testing.T) {
var s = "/start yo dawg"
var out = sanitize(s)
var expected = " yo dawg"
if expected != out {
t.Errorf("expected %s, got %s", expected, out)
}
}
func TestSanitizePunchCommand(t *testing.T) {
var s = "/punch yo dawg"
var out ... |
/*
Copyright 2011 Google 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 in writing, software
di... |
package config
import (
"os"
"time"
)
var DbString string
func init() {
time.Sleep(5 * time.Second)
println("Hello bridges db config!")
DbString = os.Getenv("MYSQL_USER") + ":" +
os.Getenv("MYSQL_PASSWORD") + "@tcp(" +
os.Getenv("MYSQL_HOST") + ")/" +
os.Getenv("MYSQL_DATABASE") + "?parseTime=true"
}
/... |
package main
import "fmt"
type Queue struct {
size int
front *Node
}
type Node struct {
value string
next *Node
}
func (q *Queue) Length() int {
return q.size
}
func (q *Queue) Enqueue(val string) {
if(q.front == nil){
q.front = &Node{val, nil}
}else{
rear := q.front
for rear.next != nil {
rear... |
package main
import (
"math"
"strconv"
)
func P4(param int) int {
reverse := func(s string) string {
rs := []rune(s)
for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
rs[i], rs[j] = rs[j], rs[i]
}
return string(rs)
}
min := int(math.Pow(10.0, float64(param-1)))
max := int(math.Pow(10.0, float64(par... |
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
)
// cli flags
var (
addrsFlag = flag.String("addrs", "localhost:7777", "CSV of setm... |
package services
import (
"encoding/json"
"github.com/shirobrak/newsapi/entities/responses"
"github.com/shirobrak/newsapi/entities/responses/contents"
)
// TopicsAPIServiceInterface is the interface for the adapter to connect.
type TopicsAPIServiceInterface interface {
SearchArticles(genre string) ([]contents.Ar... |
package main
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
)
type MerkleTree struct {
root *Node
leaves [][]byte
}
type Node struct {
data []byte
left *Node
right *Node
}
func calculateHash(leaves [][]byte) {
h := sha256.New()
length := len(leaves)
if length%2 != 0 {
leaves = app... |
package main
import "fmt"
type Planet struct {
Size int
Radius int
}
type World struct {
Planet
Name string
}
type IPlanet interface {
GetSize() int
SetSize(size int)
}
func (p *Planet) GetSize() int {
return p.Size * p.Radius
}
func (p *Planet) SetSize(size int) {
p.Size = size
}
func main() {
//var mar... |
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"os"
"os/signal"
"time"
"trlogic2/api/handlers"
)
func main() {
router := gin.Default()
router.POST("/photo", handlers.GetPhoto)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
s := &http.Server{
Addr: ... |
package CTData
import (
"crypto/sha256"
"fmt"
)
// function to compute sha256 of a []byte
func NewSHA256(data []byte) []byte {
hash := sha256.Sum256(data)
return hash[:]
}
// struct to hold all fields for a CTData message
type CTData struct{
TBS SignedFields
Signature []byte
}
// all fields in a CTData that... |
// Copyright © 2021 Attestant Limited.
// 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 commands
import (
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
"html/template"
"io/ioutil"
"os"
rice "github.com/GeertJohan/go.rice"
"github.com/gookit/color"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
)
// Random Hex
// generate n hex bytes
func randomHex(n int)... |
package db
import (
"database/sql"
"fmt"
_ "github.com/mxk/go-sqlite/sqlite3"
"os"
"os/user"
"path/filepath"
"twitter"
)
func DB() *sql.DB {
db, connErr := sql.Open("sqlite3", dbName())
if connErr != nil {
panic(connErr)
}
setupStatements := []string{
"CREATE TABLE IF NOT EXISTS tweets(id, text, user... |
package factory
import (
"fmt"
)
type defaultPokemon struct {
name string
}
// Charmander type
type Charmander struct {
defaultPokemon
}
// Pikachu type with additional struct nick
type Pikachu struct {
defaultPokemon
nick string
}
// Spawn charmander
func (c *Charmander) Spawn() {
c.defaultPokemon.name = "C... |
package provider
import (
"context"
"crypto/tls"
"sync"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gookit/gcli/v3"
cmdcommon "github.com/ovrclk/akash/cmd/common"
cltypes "github.com/ovrclk/akash/provider/cluster/types"
gwrest "github.com/ovrclk/akash/provider/gateway/rest"
cutils "github.com/ovrclk... |
package model
type RedisCommandList struct {
CommandList []*RedisCommand `json:"command_list" binding:"required"`
}
type RedisCommand struct {
Method string `json:"method" binding:"required"`
Name string `json:"name" binding:"required"`
Args string `json:"... |
package agreementbot
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/golang/glog"
"github.com/open-horizon/anax/abstractprotocol"
"github.com/open-horizon/anax/agreementbot/persistence"
"github.com/open-horizon/anax/config"
"github.com/open-horizon/anax/cutil"
"github.com/open-horizon/anax/events... |
package router
import (
"encoding/json"
"fmt"
"net/http"
"strings"
api "silverfish/router/api"
interf "silverfish/router/interface"
silverfish "silverfish/silverfish"
entity "silverfish/silverfish/entity"
"github.com/gorilla/mux"
"github.com/pkg/errors"
)
// Router export
type Router struct {
recaptchaPr... |
package secret
import (
"time"
"gopkg.in/mgo.v2/bson"
)
type Secret struct {
ID bson.ObjectId `bson:"_id" json:"-" xml:"-"`
Hash string `bson:"hash" json:"hash"`
SecretText string `bson:"secretText" json:"secretText"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
ExpiresAt time.Time `bson:"expiresAt... |
package mux
type Article struct {
Id string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
}
var articles map[string]Article
func init() {
if articles == nil {
articles = make(map[string]Article)
}
algorithm := Article{
Id: "1",
Title: "Algorithm",
Content: "Algor... |
package 字符串
import (
"strconv"
"strings"
)
// restoreIpAddresses 获取字符串中合法的IP地址。
func restoreIpAddresses(s string) []string {
result := parse(s, 1)
addresses := make([]string, 0)
for _, addressParts := range result {
addresses = append(addresses, strings.Join(addressParts, "."))
}
return addresses
}
// parse... |
package rest
import (
"crypto/tls"
"net/http"
)
// TLS abstracts the way REST interfaces TLS is configured.
type TLS interface {
// Config provides the tls.Config object to be set on server.TLSConfig
Config() (*tls.Config, error)
// ListenAndServe encapsulates the decision, whether server.ListenAndServe() or ser... |
package main
import (
"github.com/go-redis/redis"
"github.com/locpham24/go-weather/db"
"github.com/locpham24/go-weather/handler"
)
func main() {
pg := db.PgDb{}
pg.Connect()
defer pg.Close()
redisClient := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
rout... |
/*
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Constraints:
The Linked List is not empty.
Number of nodes will not exc... |
package biz
import (
v1 "fxkt.tech/bj21/api/bj21/v1"
"github.com/go-kratos/kratos/v2/log"
)
type BlackJackRepo interface {
LogicConn(srv v1.BlackJack_LogicConnServer) error
}
type BlackJackUsecase struct {
repo BlackJackRepo
log *log.Helper
}
func NewBlackJackUsecase(repo BlackJackRepo, logger log.Logger) *Bl... |
package rocketmq
import (
"context"
"fmt"
"strings"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/intstr"
middlewarev1alpha1 "github.com/riete/rocketmq-operator/pkg/apis/middleware/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
... |
/*
Copyright Mojing Inc. 2016 All Rights Reserved.
Written by mint.zhao.chiu@gmail.com. github.com: https://www.github.com/mintzhao
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.apa... |
package std
import (
"errors"
"fmt"
"time"
"gitlab.wallstcn.com/matrix/xgbkb/std/redislogger"
"gopkg.in/redis.v5"
)
type MutexInterface interface {
Lock() (bool, error)
UnLock() error
}
// =====================================================================================================================
t... |
// Copyright 2021 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package definition
import (
"fmt"
)
const (
// ConsulService const
ConsulService = "consul"
// ConsulHTTPPort const
ConsulHTTPPort = "8500"
// ConsulDockerImage ... |
package match
import (
"context"
"github.com/kumahq/kuma/pkg/core/policy"
core_mesh "github.com/kumahq/kuma/pkg/core/resources/apis/mesh"
"github.com/kumahq/kuma/pkg/core/resources/manager"
)
// Gateway selects the matching GatewayResource (if any) for the given DataplaneResorce.
func Gateway(m manager.ReadOnlyR... |
package main
import (
"fmt"
"os"
"strings"
"github.com/clagraff/argparse"
)
func main() {
parser.add_argument("--stream_vmdk",
dest=="stream_vmdk",
argparse.StoreTrue,
help=="Compress vmdk file")
parser.add_argument("--vmx",
d... |
// Copyright 2019 Yunion
//
// 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 writi... |
package config
import (
"fmt"
"net/url"
"strings"
)
func handleSymbols(getter StringGetter, key string) []string {
rawSymbols := getter(key)
rawSymbols = strings.ToUpper(rawSymbols)
splitSymbols := strings.Split(rawSymbols, ",")
return cleanList(splitSymbols)
}
func handlePushServerURL(getter StringGetter,... |
func combine(n int, k int) [][]int {
if k == 1 {
var combs [][]int
for i := 1; i < n + 1; i++ {
combs = append(combs, []int{ i })
}
return combs
}
if k == n {
var combo []int
for i := 1; i < n + 1; i++ {
combo = append(combo, i)
}
return [][]int{ combo }
}
var combinations [][]int
for _, com... |
package include
import "time"
type Book struct {
ID int64
Status int8
ImgUrl string
ISBN string
BookName string
Publisher string
Category string
Author string
Description string
CreateTime time.Time
UpdateTime time.Time
}
|
package plugins
import (
"path/filepath"
"github.com/Zenika/marcel/config"
)
// Plugin represents a plugin configuration
type Plugin struct {
URL string `json:"url"`
Versions []string `json:"versions"`
EltName string `json:"eltName"`
Name string `json:"name"`
Description string `... |
package AdSense
type AdmanagerAdexchangeAdunitReportDaily struct {
ID uint `gorm:"primary_key"`
NetworkCode string `gorm:"type:bigint(20);"`
Date string `gorm:"type:date;"`
AdExchangeSiteName string `gorm:"type:varchar(256);column:ad_exchange_site_name;"`
DeviceCategoryId string `gorm:"type:varchar(45);col... |
package repositories
import (
"encoding/json"
"errors"
"log"
"github.com/danielhood/quest.server.api/entities"
)
// TODO: Move this to somewhere better (redis?)
var players []entities.Player
func init() {
players = make([]entities.Player, 0)
}
// PlayerRepo defines interface
type PlayerRepo interface {
GetAl... |
// proc.go
package proc
import (
"sync"
)
func ProcPin() int {
return sync.ProcPin()
}
func ProcUnpin() {
sync.ProcUnpin()
}
|
/*
Introduction
I stumbled across this (useless) pattern the other day while I was watching TV. I named it "the 9 pattern" because the first number to use it was 9. The gist of it is, you enter a number (let's say x), and then you get back:
x
x + (x / 3) [let's call this y]
two-thirds of y [let's call this z]
z + 1
S... |
package handlers
import (
"InkaTry/warehouse-storage-be/internal/http/admin/dtos"
"InkaTry/warehouse-storage-be/internal/pkg/errs"
"context"
"log"
)
const logAutocomplete = "[Autocomplete]"
func (h *Handler) Autocomplete(ctx context.Context, p *dtos.AutocompleteRequest) (*dtos.AutocompleteResponse, error) {
re... |
package main
import (
"errors"
"fmt"
)
func SumSquareDiff(max int) (int, error) {
if max < 0 {
return 0, errors.New("Max value must be positive")
}
sum := 0
sumOfSquares := 0
for i := 1; i <= max; i++ {
sum += i
sumOfSquares += i * i
}
squareOfSum := sum * sum
difference := squareOfSum - sumOfSquar... |
package main
import (
"fmt"
"jblee.net/adventofcode2018/utils"
)
type groundMap [][]byte
const openLand = '.'
const trees = '|'
const lumberyard = '#'
func initEmptyMap(numCols, numRows int) *groundMap {
var theMap groundMap
theMap = make([][]byte, numCols)
for x := 0; x < numCols; x++ {
theMap[x] = make([]... |
package server
import (
"github.com/Tanibox/tania-core/src/tasks/domain"
"github.com/Tanibox/tania-core/src/tasks/storage"
)
func MapTaskToTaskRead(task *domain.Task) *storage.TaskRead {
taskRead := &storage.TaskRead{
Title: task.Title,
UID: task.UID,
Description: task.Description,
Crea... |
package controllers
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"github.com/ZootHii/blog-go-backend/api/auth"
"github.com/ZootHii/blog-go-backend/api/models"
"github.com/ZootHii/blog-go-backend/api/responses"
"github.com/ZootHii/blog-go-backend/api/utils/customerrors"
"github.c... |
package syslog
import (
"fmt"
"io"
"log"
"os"
"strings"
param "github.com/DynamoGraph/dygparam"
)
const (
logrFlags = log.LstdFlags | log.Lshortfile
)
const (
logDir = "/home/ec2-user/environment/project/DynamoGraph/log/"
logName = "GoGraph"
idFile = "log.id"
Force = true
)
// global logger - access... |
package main
import (
"fmt"
"sync"
)
func speakNumber(values map[int][]int, m []int, ok bool, n, turn int) {
m, ok = values[n]
if !ok {
values[n] = []int{turn, 0}
} else {
shift := []int{turn, m[0]}
values[n] = shift
}
}
func wasSpoken(values map[int][]int, n int) (bool, []int) {
m, ok := values[n]
if ... |
/**
* @program: Go
*
* @description:消费单列模式的对列,生成订单
*
* @author: Mr.chen
*
* @create: 2020-03-09 11:31
**/
package main
import (
"iris_demo/common"
"fmt"
"iris_demo/repositories"
"iris_demo/services"
"iris_demo/rabbitmq"
)
func main() {
db,err:=common.NewMysqlConn()
if err !=nil {
fmt.Println(err)
}
//创建... |
package main
import "fmt"
// Printer define func type
type Printer func(s string) (n int, err error)
// PrinterToStd impletement print func
func PrinterToStd(str string) (bytesNum int, err error) {
return fmt.Println(str)
}
func main() {
var p Printer
p = PrinterToStd
p("zhong")
}
|
package model
type Video struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Duration int `json:"duration"`
OwnerId string `json:"ownerId"`
Thumbnail string `json:"thumbnail"`
Status int `json:"st... |
package db
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"errors"
"sort"
"strings"
"github.com/Masterminds/squirrel"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/spf13/viper"
)
var (
gormConnection *gorm.DB
debug = false
ErrNotFound = errors.New("not found")
)
... |
// 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 parser_test
import (
"fmt"
"testing"
llp "github.com/romshark/llparser"
"github.com/stretchr/testify/require"
)
func str(format string, a ...interface{}) string {
return fmt.Sprintf(format, a...)
}
func test(t *testing.T, pattern llp.Pattern, expectedErrMsg string) {
// Wrap non-rules into dummy rules... |
package repository
import (
"strconv"
"github.com/korrawit/finalexam/database"
)
type Customer struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Status string `json:"status"`
}
type Repository struct {
DB database.Interface
}
type CustomerRepository interface {
Cre... |
package main
import "testing"
import . "../middleware"
import . "../message"
import . "../topic_manager"
func TestCreateTopicOld(t *testing.T) {
var topic Topic
tsession := TopicSession{}
topic = tsession.CreateTopic("meu_topico_massa")
topicname := topic.GetTopicName()
if topicname != "meu_topico_massa" {
... |
// 9x9 multiplication table in Go
// CC0, Wei-Lun Chao <bluebat@member.fsf.org>, 2018.
// go run mt9x9.go || ( go build mt9x9.go ; ./mt9x9 )
package main
import "fmt"
func main() {
for i := 1; i <= 9; i += 3 {
for j := 1; j <= 9; j++ {
for k := i; k < i+3; k++ {
fmt.Printf("%dx%... |
package net
import (
"errors"
"fmt"
//models "github.com/flowagent/models"
models "sysmonitor/net/models"
"net"
"os"
"strconv"
"strings"
"time"
psutilnet "github.com/shirou/gopsutil/net"
)
func isFoundInterface(eth string, eths []string) bool {
var found bool
for _, name := range eths {
if strings.Equa... |
package main
type BlockChain struct {
blocks []*Block
}
func NewBlockChain()*BlockChain {
block :=NewGenesisBlock();
return &BlockChain{[]*Block{block}}
}
func (bc *BlockChain)AddBlock(data string) {
prevBlockHash:=bc.blocks[len(bc.blocks)-1].Hash
block:=NewBlock(data,prevBlockHash)
bc.blocks=append(bc.block... |
package main
import (
"testing"
)
func TestSmallestRepetition(t *testing.T) {
if Smallestrep("d") != 1 {
t.Fatalf("expected 1")
}
if Smallestrep("dd") != 1 {
t.Fatalf("expected 1")
}
if Smallestrep("ddd") != 1 {
t.Fatalf("expected 1")
}
if Smallestrep("dad") != ... |
package main
import (
"log"
"os"
"github.com/urfave/cli"
)
var app = cli.NewApp()
var db = newDB(":memory:")
func initApp() {
info()
commands()
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func info() {
app.Name = "URL shortening API"
app.Usage = "Can shorten a full URL"
app.Author = "R... |
package Problem0529
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
board [][]byte
click []int
ans [][]byte
}{
{
[][]byte{
{'E', 'E', 'E', 'E', 'E'},
{'E', 'E', 'M', 'E', 'E'},
{'E', 'E', 'E', 'E', 'E'},
{'E', 'E', 'E', 'E', 'E'}},... |
package logger
import (
"fmt"
"os"
"path"
"regexp"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/gorilla/websocket"
)
// Logger 应用使用的 logger 实例
var Logger = logrus.New().WithField("name", "haruno")
// LogTypeInfo 信息类型
const LogTypeInfo = 0
// LogTypeError 错误类型
const LogTypeError = 1
// LogTypeSu... |
package mocks
import (
"encoding/json"
"errors"
"log"
"reflect"
"testing"
"github.com/b-2019-apt-test/divider/internal/divider"
"github.com/b-2019-apt-test/divider/pkg/div/godiv"
)
var (
// FakeLog is used with mocked JobProcessor.
// By default it uses writer that drops messages.
FakeLog = log.New(NewFake... |
package main
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
func crawl(q string) {
timeout := time.Duration(5 * time.Second) //超时时间5s
client := &http.Client{
Timeout: timeout,
}
url := "https://pkg.go.dev/search?q=" + q
var Body io.Reader
request, er... |
package urlshort
import (
"database/sql"
"fmt"
"net/http"
_ "github.com/lib/pq"
)
func SQLHandler(fallback http.Handler) http.HandlerFunc {
fmt.Println("yepppp")
connStr := "user=postgres password=asdfasdf dbname=urlshort sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err... |
package config
import (
"encoding/json"
"github.com/zalando-incubator/postgres-operator/pkg/spec"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/mohae/deepcopy"
)
type OperatorConfiguration struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metad... |
package main
import (
"net/http"
_ "github.com/go-sql-driver/mysql"
"html/template"
"os"
"io/ioutil"
"github.com/julienschmidt/httprouter"
"github.com/controller"
"github.com/database"
"github.com/api/v1"
)
var templates map[string]*template.Template
var db database.Mysql
var router v1.Router
func main() {
... |
package main
import (
"fmt"
"log"
"net/http"
"commontest/Config"
"commontest/controllers"
"github.com/gorilla/mux"
)
func main() {
config, err := Config.InitConfig()
if err != nil {
fmt.Println(err)
}
general := controllers.NewGeneral(config)
test := controllers.NewTestController(config)
result := cont... |
package day18
type Queue struct {
head *Node
tail *Node
length int
}
func (q Queue) NewQueue() Queue {
return Queue{}
}
func (q *Queue) EnQueue(data rune) {
node := Node{}.NewNode(data)
if q.head == nil {
q.head = node
q.tail = q.head
} else {
q.tail.next = node
q.tail = node
}
q.length++
}
fun... |
package postgres
import (
"context"
"encoding/json"
"time"
"gorm.io/datatypes"
"github.com/google/uuid"
"github.com/odpf/optimus/models"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type BackupDetail struct {
Result map[string]interface{}
Description string
Config map[string]string
}
type Backup s... |
package geo
type Property interface{}
type PropertyCollection []interface{}
type Properties map[string]Property
type PropertyCollections map[string]PropertyCollection
func (pcs PropertyCollections) AppendProperties(ps Properties) {
for key, property := range ps {
if _, ok := pcs[key]; !ok {
pcs[key] = Property... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.