text stringlengths 11 4.05M |
|---|
package service
import (
"encoding/json"
"fmt"
"time"
"github.com/go-ocf/kit/net/grpc"
)
//Config represent application configuration
type Config struct {
grpc.Config
AuthServerAddr string `envconfig:"AUTH_SERVER_ADDRESS" default:"127.0.0.1:9100"`
ResourceAggregateAddr string `envconfig:"... |
// Copyright 2017 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 infra
import (
"chatapp/util/logger"
"context"
)
func Setup() {
err := GetRedis().Info(context.Background(), "server").Err()
if err != nil {
panic(err)
} else {
logger.Get().Info("Redis-server: connected.")
}
}
|
/*
A fruit juice company tags their fruit juices by concatenating the first three letters of the words in a flavor's name and its capacity.
Create a function that creates the product IDs for the variety of fruit juices.
Examples
getDrinkID("apple", "500ml") ➞ "APP500"
getDrinkID("pineapple", "45ml") ➞ "PIN45"
get... |
package ziface
/*
封包、拆包 模块
直接面向TCP 连接的数据流,用于处理 TCP 粘包问题
*/
type IDataPack interface {
// 获取包的头的长度的方法
GetHandLen() uint32
// 封包方法
Pack(msg IMessage)([]byte,error)
// 拆包方法
Unpack([]byte)(IMessage,error)
}
|
package fingerprint
import (
"bytes"
"encoding/json"
"errors"
"os"
"os/exec"
"path"
"path/filepath"
"sync"
"github.com/spf13/afero"
)
var (
ValidAudioFormats = []string{".mp3"}
)
type ExecCmd = func(name string, arg ...string) *exec.Cmd
// ChromaPrint is a concrete implementation of the Fingerprinter int... |
// Copyright 2023 Google LLC. 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 applica... |
package serverutil
type Context interface {
Pipeline() Pipeline
Prev() Context
Next() Context
InputHandler() InputHandler
OutputHandler() OutputHandler
ErrorHandler() ErrorHandler
OnRead(rawMsg interface{}) chan bool
OnWrite(rawMsg interface{}) chan bool
OnError(err error) chan bool
OnClose()
... |
package form
import (
"reflect"
"testing"
. "github.com/go-playground/assert/v2"
)
// NOTES:
// - Run "go test" to run tests
// - Run "gocov test | gocov report" to report on test converage by file
// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never c... |
package queue
// Task you should implement
type Task interface {
Run() error
}
// PriorityTask ..
type PriorityTask interface {
Comparator
Run() error
}
// Comparator like the java Comparator
type Comparator interface {
Less(i interface{}) bool
}
|
package server
import (
"params"
)
func getMqService(param params.Init) params.MqSrv {
return param.MqClient
}
func getRespService(param params.Init) params.RespSrv {
return param.RespClient
} |
package src
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_it_allows_mark_a_non_take_position(t *testing.T) {
game := NewGame()
error := game.Play(1, 1)
assert.NoError(t, error)
}
func Test_the_board_is_a_3_x_3_grid(t *testing.T) {
game := NewGame()
assert.Equal(t, "[[ ] [ ] [ ]]", ga... |
package main
import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
stdin, err := FetchStdin()
if err != nil {
panic(err)
}
// fmt.Println(stdin)
data, err := makeAssignmentData(stdin)
if err != nil {
panic(err)
}
PrintStruct(data)
output := countAllHalve(data.values)
fmt.Print... |
/*
* product: matrix-vector product
*
* input:
* nelts: the number of elements
* Outer_matrix: the real matrix
* Outer_vector: the real vector
*
* output:
* Product_result: a real vector, whose values are the result of the product
*/
package all
var Product_result []Double;
func fill_result_impl(beg... |
package dog
import (
"fmt"
"testing"
)
func TestYears(t *testing.T) {
type test struct {
data int
result int
testname string
}
tests := []test{
{
data: 2,
result: 14,
testname: "YearsT1",
},
{
data: 5,
result: 35,
testname: "YearsT2",
},
}
for _, v := range ... |
package main
import (
"net/http"
"github.com/riyadennis/goophercises/testing/signal"
)
func main() {
http.HandleFunc("/handle", signal.Handler)
http.ListenAndServe(":8080", nil)
}
|
/*
闭包的作用有1,模拟一个缓存变量,2,封装,外部不能直接访问到缓存变量,因为变量被定义在闭包作用域中。
如下的x,在每次调用闭包函数后,x都会被改变,x这个变量不会给垃圾回收器回收。切外部不能直接访问到x。
实现闭包一般是在非面向对象的语言中,在一个函数中定义一个函数,并返回这个函数。
*/
package main
import (
"fmt"
)
func main() {
f := closure(10)
fmt.Println(f(1)) //11
fmt.Println(f(2)) //13
}
func closure(x int) func(int) int {
return func(y... |
package generic
import (
"encoding/csv"
"fmt"
"log"
"os"
"path/filepath"
"time"
kcp "github.com/xtaci/kcp-go/v5"
)
func SnmpLogger(path string, interval int) {
if path == "" || interval == 0 {
return
}
ticker := time.NewTicker(time.Duration(interval) * time.Second)
defer ticker.Stop()
for {
select {
... |
package main
import (
"log"
"net/http"
"time"
"github.com/Benzinga/go-webrpc"
)
func main() {
log.Println("Server starting.")
server := webrpc.NewServer()
server.OnConnect(func(c *webrpc.Conn) {
user := c.Addr().String()
log.Println(user, "connected")
join := func(ch string) {
c.Join(ch)
server.... |
package responses
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// IonResponse represents the response structure expected back from the Ion
// Channel API calls
type IonResponse struct {
Data json.RawMessage `json:"data"`
Meta Meta `json:"meta"`
status int
}
// Meta represents t... |
package message
import (
"github.com/streadway/amqp"
)
type Message interface {
ExchangeDeclare(options ...ExchangeOption) error
QueueDeclare(options ...QueueOption) (string, error)
Publish(options ...PublishOption) error
Consume(options ...ConsumeOption) (<-chan amqp.Delivery, error)
CloseChannel() error
}
|
package validation
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestController_Process(t *testing.T) {
type fields struct {
ValidatePayload func(p *Payload) error
}
type args struct {
w http.ResponseWriter
r *http.Request
}
tests := []struct {
name string
fields fiel... |
package utils
import (
"BcRPCCode/entity"
"BeegoBcRPCCode/models"
"encoding/json"
"fmt"
)
//获取当前节点的区块个数
func GetBlockcount() float64 {
resByte := RpcRequest("getblockcount")
//fmt.Println(string(resByte))
var rpcResult models.RPCResult
err := json.Unmarshal(resByte, &rpcResult)
if err != nil {
fmt.Println(... |
/*
Copyright 2015 OpsGenie. All rights reserved.
Use of this source code is governed by a Apache Software
license that can be found in the LICENSE file.
*/
//Package cfg reads configurations and provides configuration props to commands.
package cfg
import (
"fmt"
"github.com/ccding/go-config-reader/config"
"os"
"... |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
m := map[int]string{0: "green", 1: "yellow", 2: "red"}
for i := 0; i < 3; i++ {
c := make(chan string)
go sendColor(m[rand.Intn(len(m))], c)
go receiveColor(c)
}
<-time.After(10 * time.Second)
}
func sendCol... |
package _47_Permutations_2
import (
"sort"
)
func permuteUnique(nums []int) [][]int {
ret := [][]int{}
sort.Ints(nums)
used := []bool{}
for i := 0; i < len(nums); i++ {
used = append(used, false)
}
backtrack(&ret, &[]int{}, nums, &used)
return ret
}
func backtrack(list *[][]int, tmpList *[]int, nums []int,... |
package gcp
import (
"context"
"github.com/pkg/errors"
compute "google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
)
func (o *ClusterUninstaller) listNetworks(ctx context.Context) ([]cloudResource, error) {
return o.listNetworksWithFilter(ctx, "items(name,selfLink),nextPageToken", o.clusterIDFi... |
package orm_old
import (
"fmt"
"sync"
"testing"
"github.com/go-xorm/xorm"
"github.com/teejays/clog"
)
var gTestSession *xorm.Session
var gTestSessionLock sync.RWMutex
func StartTestSession() error {
gTestSessionLock.Lock()
defer gTestSessionLock.Unlock()
if gTestSession != nil {
return fmt.Errorf("orm: te... |
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
"github.com/kataras/iris/v12/middleware/recover"
"github.com/kataras/iris/v12/sessions"
//"github.com/kataras/iris/v12/core/router"
)
var (
cookieNameForSessionID = "mycookiesessionnameid"
sess ... |
package controller
type RobotInfo struct {
RobotWxNick string `json:"robot"`
RunTime int64 `json:"runTime"`
}
type RobotFindFriendReq struct {
WechatNick string `json:"wechatNick"`
UserName string `json:"username"`
NickName string `json:"nickname"`
}
type RobotRemarkFriendReq struct {
WechatNick strin... |
package files
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var (
// ErrExpectedStdin indicates that an stdin pipe was expected but not present
ErrExpectedStdin = errors.New("expected a pipe stdin")
)
// ReadInput reads bytes from inputPath (if not emp... |
package main
import (
"os"
"os/signal"
"syscall"
)
type Trade struct {
Type string
Price float32 `json:"price"`
Amount float32 `json:"amount"`
Tid int `json:"tid"`
Timestamp int64 `json:"timestamp"`
}
type Trades struct {
LeTrades []Trade `json:"ltc_usd"`
}
func checkError(e error) ... |
// Copyright (c) 2019 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package ssh
import (
"bufio"
"regexp"
"strings"
"testing"
"github.com/vladimirvivien/gexe"
)
func TestParseAndValidateAgentInfo(t *testing.T) {
tests := []struct {
name string
info string
shouldErr b... |
package dbsrv
import (
"database/sql"
"fmt"
slog "log"
"os"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/empirefox/esecend/config"
"github.com/empirefox/esecend/front"
"github.com/empirefox/esecend/wx"
"github.com/empirefox/reform"
"github.com/empirefox/reform/dialects/mysql"
_ "github.com/go-s... |
package inmemory_test
import (
"testing"
"github.com/Tinee/go-graphql-chat/domain"
)
func Test_profileInMemory_Create(t *testing.T) {
c := NewClient()
repo := c.ProfileRepository()
p, err := repo.Create(domain.Profile{
Age: 25,
FirstName: "Foo",
LastName: "Bar",
UserID: "Test",
})
if err !... |
package main_test
import (
"encoding/json"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs/cloudwatchlogsiface"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
"github.com/flow-lab/dlog"
"github.com/flow-lab/log-group-subscriber"
"github.com/stretchr/... |
package main
import "fmt"
func hello2(ch chan int) {
ch<-3
}
func main() {
ch := make(chan int)
go hello2(ch);
fmt.Println(<-ch)
}
|
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "rest-client",
Short: "CLI REST client compatible with JetBrains REST c... |
package consul
import (
"context"
"fmt"
"time"
consulAPI "github.com/hashicorp/consul/api"
)
var ErrAbsentServiceRegisterConfig = fmt.Errorf("service register config is absent")
// Register implements registry Client interface
func (client *Client) Register() error {
if client.registryConfig == nil {
return ... |
package main
import (
"awesomeProject1/database"
"awesomeProject1/routes"
"github.com/gorilla/mux"
_ "github.com/jackc/pgx/v4/stdlib"
"log"
"net/http"
)
func main() {
database.ConnectDB()
defer database.DB.Close()
r := mux.NewRouter()
routes.RegisterRoutes(r)
log.Fatal(http.ListenAndServe(":8080", r))
}... |
package discovery
import (
"testing"
"github.com/hashicorp/consul/api"
)
func TestNewClient(t *testing.T) {
type args struct {
config *api.Config
address string
name string
port int
}
tests := []struct {
name string
args args
wantErr bool
}{
{"base-case", args{api.DefaultConfig(), ... |
package models
import (
"time"
)
type Item struct {
ID uint64 `json:"id" gorm:"column:id;primary_key"`
UserID uint64 `json:"user_id" gorm:"column:user_id" sql:"not null;index;type:bigint(20)"`
GithubURL string `json:"github_url" gorm:"column:github_url" sql:"defau... |
package leetcode
import (
"reflect"
"testing"
)
func TestCombinationSum(t *testing.T) {
tests := []struct {
candidates []int
target int
answer [][]int
}{
{
candidates: []int{2, 3, 6, 7},
target: 7,
answer: [][]int{
{7},
{2, 2, 3},
},
},
{
candidates: []int{2, 3, 5},
... |
package iirepo
import (
"fmt"
)
// NotFound is an error that is returned by Locate(), and LocateRoot() if they cannot locate
// what they are looking for.
//
// Here is an example of with iirepo.LocateRoot():
//
// import "github.com/reiver/go-iirepo"
//
// // ...
//
// rootpath, err := iirepo.LocateRoot()
// if... |
package listen
import (
"github.com/gin-gonic/gin"
"net/http"
"tanglei_1211/messageboard/lv1/handle"
)
func Register(userinfo *gin.Context) {
res := handle.Register(userinfo)
if res {
userinfo.JSON(http.StatusOK, gin.H{
"code": 2020,
"message": "success",
})
} else {
userinfo.JSON(http.StatusOK,... |
package network
import (
"reflect"
"sync"
"github.com/perlin-network/noise/crypto"
"github.com/perlin-network/noise/crypto/hashing/blake2b"
"github.com/perlin-network/noise/crypto/signing/ed25519"
"github.com/perlin-network/noise/peer"
"github.com/perlin-network/noise/protobuf"
"github.com/pkg/errors"
)
// ... |
package main
import (
// "fmt"
"os"
"os/signal"
"syscall"
"strings"
"io/ioutil"
"net/http"
"encoding/json"
"log"
"github.com/bwmarrin/discordgo"
)
//
// Greg
//
type Greg struct {
Session *discordgo.Session
BotToken string
BotPrefix []string
}
type GregChannel struct {
Name string
... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/signal"
"path"
"path/filepath"
"strings"
"syscall"
docker "github.com/fsouza/go-dockerclient"
"github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
"github.com/fatih/color"
"gopkg.in/urfave/cli.v1"
"gopkg.in/yaml.v2"
)
// CorkDef... |
package core
import (
"testing"
"github.com/grayzone/godcm/util"
)
func TestDcmReaderReadFileNONDICOM(t *testing.T) {
cases := []struct {
in string
want DcmDataset
}{
{"", DcmDataset{}},
{util.GetTestDataFolder() + "minimumdict.xml", DcmDataset{}},
}
for _, c := range cases {
var reader DcmReader
... |
package dcmdata
/// index indicating "end of list"
const DCM_EndOfListIndex = -1
/** helper class maintaining an entry in a DcmList double-linked list
*/
type DcmListNode struct {
/// pointer to next node in double-linked list
nextNode *DcmListNode
/// pointer to previous node in double-linked list
prevNode *Dc... |
/*
* Copyright (c) YugaByte, Inc.
*/
package common
// Component interface used by all services and
// the Common class (general operations not performed
// specific to a service).
type Component interface {
TemplateFile() string
Name() string
Uninstall(cleanData bool)
Upgrade()
Status() Status
Start()
Stop(... |
/* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* contributed by Krzysztof Kowalczyk
*/
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
"time"
)
var comptbl = [256]uint8{}
func build_comptbl() {
l1 := []byte("UACBDKRWSN")
l2 := []byte("ATGVHMYWSN")
l1_lower := bytes.... |
package model
// Partner ...
type Partner struct {
ID string
Capacity int
TheatreTariffs []TheatreTariff
}
func (p *Partner) AddTheatreTariff(theatre Theatre, tariff Tariff) {
if p.TheatreTariffs == nil {
p.TheatreTariffs = make([]TheatreTariff, 0)
}
for i := 0; i < len(p.TheatreTariffs); i... |
// tgbot-go
// https://github.com/modern-dev/tgbot-go
// Copyright (c) 2020 Bohdan Shtepan
// Licensed under the MIT license.
package tgbot
import "strconv"
type SendMessageOptions struct {
DisableWebPagePreview bool
DisableNotification bool
ReplyToMessageId int
ReplyMarkup string
}
func (smo *... |
package main
// storage and loading of categories
import (
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/kylelemons/go-gypsy/yaml"
)
// A weight contains the point values assigned to a rule+category combination.
type weight struct {
points int // points per occurrence
maxPoints int // ma... |
package symboltable
type StringToIntST interface {
Put(key string, val int)
Get(key string) (int, bool)
Delete(key string)
}
|
package server
import (
"Go-Server/model"
"Go-Server/server/utils"
"fmt"
"github.com/gorilla/mux"
"net/http"
)
type Server struct {
port string
isHelpMode bool
connections []*utils.Connection
router *mux.Router
jdb *model.JsonDatabase
}
func (server *Server) Run(isHelpMode bool) {
ser... |
package str
import (
"strings"
)
func ToENSymbol(raw string) string {
raw = strings.Replace(raw, ",", ",", -1)
raw = strings.Replace(raw, "(", "(", -1)
raw = strings.Replace(raw, ")", ")", -1)
raw = strings.Replace(raw, ":", ":", -1)
raw = strings.Replace(raw, "。", ".", -1)
return raw
}
|
// Copyright 2020 MongoDB 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... |
/*
Slice is a variable-length sequence which stores elements of a similar type,
you are not allowed to store different type of elements in the same slice.
It is just like an array having an index value and length, but the size of the
slice is resized they are not in fixed-size just like an array
*/
package main
impo... |
/**
一定要记得在confin.json配置这个模块的参数,否则无法使用
*/
package gate
import (
"github.com/dming/lodos/conf"
"github.com/dming/lodos/module"
"github.com/dming/lodos/gate/base"
)
var Module = func() module.Module {
gate := new(Gate)
return gate
}
type Gate struct {
basegate.Gate //继承
//storage map[string]map[string]string
/... |
package queue
import (
"fmt"
"testing"
)
var queue *Queue
func init() {
queue = NewQueue()
}
func TestIsEmpty(t *testing.T) {
fmt.Println(queue.IsEmpty())
}
func BenchmarkEnQueue(b *testing.B) {
for i := 0; i < b.N; i++ {
queue.EnQueue(i)
}
}
func BenchmarkDnQueue(b *testing.B) {
for i := 0; i < b.N; i++... |
# https://leetcode.com/problems/first-bad-version/
- シンプルな二分探索
- 実装の練習になった
- 左右の範囲を更新していく
- 境界値
- 更新時に左右どちらかは +1 必要
- 左端か右端に答えがあるケースでチェックすると良い
|
package day03
import "fmt"
func StandIO() {
var name string
var age int
fmt.Println("请输入")
//fmt.Scanf("name = %s age = %d", &name, &age) //以指定格式输入
/*
fmt.Scanf("%s+%d", &name, &age)
Bug: 所有输入都会识别为字符串
Debug: %d+%s
*/
//fmt.Scanln(&name, &age)
fmt.Scan(&name, &age)
fmt.Printf("name = %s\t age = %d", ... |
package main
import "fmt"
func log(inf interface{}) {
fmt.Println(inf)
}
func alumnoEsAprobado(cal1, cal2 float32) bool {
defer fmt.Println("Imprimiendo media...") // skip
defer fmt.Println("Otra cosa")
defer log("Epale!")
fmt.Println("Entrando a funcion para verificar si un alumno es aprobado")
media := (cal... |
package mylog
import (
"testing"
)
func TestFileLogger(t *testing.T) {
logger := NewFileLogger(LogLevelDebug, "/Users/zhaofan/Desktop/zz/logs","test")
logger.Debug("test debug log")
logger.Warn("test warn log")
logger.Fatal("test fatal log")
logger.Error("test error log")
logger.Info("test info log")
logger.C... |
package templater
import (
"bytes"
"text/template"
"github.com/go-task/task/v2/internal/taskfile"
)
// Templater is a help struct that allow us to call "replaceX" funcs multiple
// times, without having to check for error each time. The first error that
// happen will be assigned to r.err, and consecutive calls t... |
package orm_old
import (
"time"
"github.com/teejays/n-factor-vault/backend/library/id"
)
// BaseModel is the parent model that any struct intending to use ORM should embed.
// This ensures that we have common meta fields across all entities and makes our code DRY.
type BaseModel struct {
ID id.ID `xo... |
package main
import (
"encoding/json"
"html/template"
"log"
"net/http"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
func index(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("template/base.html"))... |
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package glue_test
import (
"bytes"
"io"
"strings"
"testing"
"github.com/fatih/color"
"github.com/pingcap/tidb/br/pkg/glue"
"github.com/stretchr/testify/require"
)
func TestColorfulTUIFunctions(t *testing.T) {
// when testing, the teriminal would be ... |
package rest
import (
"encoding/json"
"fmt"
)
type OAuthReq struct {
Code string `json:"code"`
Client_id string `json:"client_id"`
Creator_account_id string `json:"creator_account_id"`
Creator_extension_id string `json:"creator_extension_id"`
}
func (resp OAuthReq) String()... |
package compute
import "testing"
// List SSL domain certificates (successful).
func TestClient_ListSSLDomainCertificatesInNetworkDomain_Success(test *testing.T) {
testClientRequest(test, &ClientTestConfig{
Request: func(test *testing.T, client *Client) {
const networkDomainID = "14dbfacf-0e ec-4964-a0c2-ff3f739... |
package router
import (
"errors"
"github.com/ijidan/jgo/jgo/jcontext"
"github.com/ijidan/jgo/jgo/jutils"
"github.com/ijidan/jnet/jnet"
"log"
"strings"
)
//日志中间件
func LogMiddleware(c *jcontext.Context) (next bool, err error) {
log.Println("日志中间件....")
return true, nil
}
//同步cookie中间件
func BridgeAccountCookieS... |
package models
import (
"gopkg.in/mgo.v2/bson"
"time"
)
type Todo struct {
ID bson.ObjectId `bson:"_id" json:"id"`
Name string `bson:"name" json:"name"`
CreatedAt time.Time `bson:"created_at" json:"created_at"`
UpdatedAt time.Time `bson:"updated_at" json:"updated_at"`
}
|
package database
import (
. "go-be/models"
"log"
"os"
_ "gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var DB *gorm.DB
func InitDB() (*gorm.DB, error) {
log.Println("DB init")
sqliteFile := "db.sqlite3"
os.Remove(sqliteFile)
db, err := gorm.Open(sqlite.Open(sqliteFile), &gorm.Config{})
/... |
package contents
import "time"
// Article is the content of the article.
type Article struct {
Title string `json:"title"`
Summary string `json:"summary"`
URL string `json:"url"`
ImageURL string `json:"img_url"`
PublishedAt time.Time `json:"published_at"`
}
|
// Copyright 2023 Google LLC. 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 applica... |
// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
package resolvers
import (
"context"
"github.com/syncromatics/kafmesh/internal/graph/generated"
"github.com/syncromatics/kafmesh/internal/graph/model"
"github.com/pkg/errors"
)
//go:generate mockgen -source=./component.go -destination=./component_mock_test.go -package=resolvers_test
// ComponentLoader is the d... |
package apitest
import (
"fmt"
"net/http"
"testing"
)
func TestApiTest_Assert_StatusCodes(t *testing.T) {
tests := []struct {
responseStatus []int
assertFunc Assert
}{
{[]int{200, 312, 399}, IsSuccess},
{[]int{400, 404, 499}, IsClientError},
{[]int{500, 503}, IsServerError},
}
for _, test := rang... |
package pathfileops
import (
"testing"
"time"
)
func TestDirectoryTreeInfo_CopyToDirectoryTree_01(t *testing.T) {
fh := FileHelper{}
dir := fh.AdjustPathSlash("../testsrcdir")
searchPattern := ""
filesOlderThan := time.Time{}
filesNewerThan := time.Time{}
dMgr, err := DirMgr{}.New(dir)
if err !=... |
package provider
import (
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/mrparkers/terraform-provider-keycloak/keycloak"
)
func resourceKeycloakGenericClientRoleMapper() *schema.Resource {
return &schema.Resource{
Create: resourceKeycloakGenericClientRoleMapperCreate,... |
package main
import (
"log"
)
func main() {
log.SetPrefix("日志输出的例子:") //日志前缀
log.SetFlags(log.LstdFlags | log.Lmicroseconds) //日志格式
//打印错误日志,黄色字体
log.Printf("%c[33m %s %c[0m", 0x1B, "this is the error log!", 0x1B)
//打印异常日志,红色字体
log.Fatalf("%c[31m %s %c[0m", 0x1B, "this is the panic log!",... |
package main
import "C"
//export Add
func Add(x, y int) int {
return x + y
}
//export GetInt
func GetInt() int {
return 42
}
//export GetString
func GetString() string {
return "A string from Go!"
}
func main() {
// needed but not used
} |
package cis
import (
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/antonioalfa22/egida/pkg/ansible"
"github.com/antonioalfa22/go-utils/collections"
)
func ShowSectionsMenu(connection string) {
var sections []string
prompt := &survey.MultiSelect{
Message: "Select CIS Sections:",
Options: []string... |
package model
import (
"crypto/rand"
"database/sql"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
func TestWebAuthnDeviceImportExport(t *testing.T) {
have := WebAuthnDeviceExport{
WebAuthnDevices: []WebAuthnDevice{... |
package mutex_map
import "sync"
type RWSet struct {
mx sync.RWMutex
m map[int]float64
}
func NewRWSet() *RWSet {
return &RWSet{
m: map[int]float64{},
}
}
func (set *RWSet) Get(key int) (float64, bool) {
set.mx.RLock()
defer set.mx.RUnlock()
val, ok := set.m[key]
return val, ok
}
func (set *RWSet) Has(key... |
package rest
import (
"errors"
"fmt"
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/kataras/iris/v12"
)
// RegionBody 区域的body
type RegionBody struct {
UserID int32 `json:"user_id"`
Region *int32 `json:"region"`
}
cons... |
package client
import (
"errors"
"github.com/wish/ctl/pkg/client/types"
)
// Helpers for finding a specific config map
func (c *Client) findConfigMap(contexts []string, namespace, name string, options ListOptions) (*types.ConfigMapDiscovery, error) {
list, err := c.ListConfigMapsOverContexts(contexts, namespace, o... |
package util
import (
"net"
"strings"
)
// LoatlIP is make local ip
var LoatlIP string
// GetIP is get local ip
func GetIP() {
addrs, err := net.InterfaceAddrs()
if err != nil {
panic(err)
}
LoatlIP = strings.Split(addrs[1].String(), "/")[0]
CustomLogger("local ip:", LoatlIP)
}
|
package utils
import "fmt"
func RectToParcels(x1, y1, x2, y2, max int) []string {
minmax := func(x, y int) (int, int) {
if x < y {
return x, y
}
return y, x
}
x1, x2 = minmax(x1, x2)
y1, y2 = minmax(y1, y2)
size := (x2 - x1 + 1) * (y2 - y1 + 1)
if size > max {
return nil
}
ret := make([]string, ... |
package web
import (
"fmt"
"html"
"net/http"
)
func GetHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello, %q", html.EscapeString(r.URL.Path))
}
// func GetUsers(w http.ResponseWriter, r *http.Request) {
// userName := r.URL.Query().Get("user")
// w.Header().Set("Content-Type", "application... |
package cmd
import (
"os"
"github.com/Sirupsen/logrus"
"github.com/sky0621/go-testcode-autogen/_example/sampleproject"
"github.com/sky0621/go-testcode-autogen/_example/sampleproject/config"
)
func main() {
code := realMain()
logrus.Infof("ExitCode: %v", code)
os.Exit(int(code))
}
func realMain() (exitCode in... |
package orders
import (
context "context"
"time"
)
type Usecase struct {
Repo DomainRepository
ContextTimeout time.Duration
}
func NewUsecase(repo DomainRepository, timeout time.Duration) *Usecase {
return &Usecase{
Repo: repo,
ContextTimeout: timeout,
}
}
func (u *Usecase) GetAll(ctx ... |
/* _ _
*__ _____ __ ___ ___ __ _| |_ ___
*\ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
* \ V V / __/ (_| |\ V /| | (_| | || __/
* \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
*
* Copyright © 2016 - 2019 Weaviate. All rights reserved.
* LICENSE: https://github.com/semi-techno... |
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"net"
"math/rand"
"time"
"log"
"os"
"sync"
"crypto/md5"
"encoding/hex"
)
var number chan int=make(chan int,10);
var isSuccess int=0;
var lock *sync.RWMutex;
/*成功与失败*/
func main() {
//正确密码
lock=new (sync.RWMutex)
for {
if(isSuccess==1){
log.Fatal... |
package main
import (
"fmt"
)
func generateCollector(done chan<- bool) chan<- string {
receiver := make(chan string, 99)
go func() {
for newItem := range receiver {
fmt.Println(newItem)
}
// TODO: save file
// signal we are done saving
done <- true
}()
return receiver
}
|
package main
import (
"fmt"
"log"
"net/http"
"github.com/geekakili/portside/driver"
"github.com/geekakili/portside/handlers/httphandler"
)
func main() {
dbConnection, err := driver.ConnectBadger("./badger")
defer dbConnection.Badger.Close()
if err != nil {
log.Fatal(err)
}
router, err := httphandler.Se... |
package oidc_test
import (
"context"
"errors"
"net/url"
"regexp"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/oauth2"
"github.com/ory/fosite/storage"
"github.com/ory/fosite/token/hmac"
"github.com/stretchr/testify/assert"
"github.com/stretchr/tes... |
package main
//
//func main() {
// // 建立索引
// index := juno.NewIndex("")
//
// // 查询
// query := juno.NewQuery("")// 构建查询
// juno.NewQuery("")
// q := NewQuery(NewAndExpress(
// NewEqExpression("country", "us"),
// NewRangeExpression("price", 1, 20),
// NewOrExpress(
// NewEqExpression("country", "us"),
// NewIn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.