text stringlengths 11 4.05M |
|---|
package main
import (
"net/http"
"time"
)
func Racer(a, b string) (winner string) {
// startA := time.Now()
// http.Get(a)
// aDuration := time.Since(startA)
// startB := time.Now()
// http.Get(b)
// bDuration := time.Since(startB)
// if aDuration < bDuration {
// // a 的时间小于b
// return a
// }
// ret... |
package database
import (
"context"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
// DBConn returns a mongo connection.
func DBConn() (*mongo.Database, error) {
client, err := mongo.NewClient(options.Client().ApplyURI(viper.GetString("database_... |
package redis
import (
iface "KServer/library/kiface/iredis"
"fmt"
"github.com/garyburd/redigo/redis"
)
type Pool struct {
MasterPool *redis.Pool
SlavePool *redis.Pool
MasterEnable bool
SlaveEnable bool
}
func NewIRedisPool() iface.IRedisPool {
return &Pool{SlaveEnable: false, MasterEnable: false}
}
/... |
package main
import "fmt"
func main() {
// สร้างตัวแปร แบบที่ 1 ต้องระบุ type ทุกครั้ง
var x string = "Hello World"
fmt.Println(x)
x = "oil"
fmt.Println(x)
var y string = "hello"
var z string = "world"
fmt.Println(y == z)
// สร้างตัวแปร แบบที่ 2
o := "hello world"
fmt.Println(o)
}
|
package core
import (
"context"
"testing"
"time"
"github.com/jybbang/go-core-architecture/core"
)
func Test_mediator_Send(t *testing.T) {
ctx := context.Background()
m := core.NewMediatorBuilder().
AddHandler(new(okCommand), okCommandHandler).
AddHandler(new(errCommand), errCommandHandler).
Create()
ex... |
// Copyright 2019 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 clcv2
import (
"fmt"
"net"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
)
// PortSpecs implements the flag.Value interface for Port, allowing to use flags repeatedly.
type PortSpecs []Port
// PortSpecString is a Port to be used for other applications
type PortSpecString PortSpecs
// MarshalJS... |
package stmanager_test
import(
"testing"
"manager/stmanager"
)
func Test_SZSECompanyManager_Process(t *testing.T){
m := stmanager.NewSZSECompanyManager()
m.Process()
}
|
package admin
import (
"bytes"
"crypto/md5"
"fmt"
"io"
)
func Md5Pass(s string) string {
md5Password := md5.New()
io.WriteString(md5Password, s)
buffer := bytes.NewBuffer(nil)
fmt.Fprintf(buffer, "%x", md5Password.Sum(nil))
newPass := buffer.String()
return newPass
}
|
package main
import "fmt"
func main() {
// define map
emails := make(map[string]string)
// assing key value
emails["Bob"] = "bob@gmail.com"
emails["Truong"] = "truong@gmail.com"
emails["Mike"] = "mike@gmail.com"
fmt.Println(emails)
fmt.Println(len(emails))
fmt.Println(emails["Truong"])
// delete
delete(e... |
package main
import (
"testing"
"os"
)
func TestGetMd5FromFile(t *testing.T){
t.Run("md5Verify", func(t *testing.T){
f,_ := os.Open("resource/testMd5.txt")
md5Str := getMd5FromFile(f)
if md5Str != "a906449d5769fa7361d7ecc6aa3f6d28"{
t.Fail()
}
})
}
|
package wire
import (
"bytes"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol"
"gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/utils"
"testing"
)
func TestWire(t *testing.T) {
RegisterFailHandler(... |
package main
import (
"log"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
type Module3rdTestSuite struct {
suite.Suite
modules3rd []Module3rd
}
func (suite *Module3rdTestSuite) SetupTest() {
modules3rdConf := "./config/modules.cfg.example"
modules3rd, err := loadModule... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
var (
corpID = ""
corpSecret = ""
agentID = "1000002"
tokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +
corpID + "&corpsecret=" + corpSecret
sendClient = &http.Client{Timeout: 10 * time.Second}
msgTo ... |
package awsclient
import (
"fmt"
"io"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
)
// S3Client - manages a persistent connection with downstream S3 bucket
type S3Client struct {
s3Manager... |
package dcraw
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os/exec"
)
var binPath string = "dcraw-json"
// SetDCRawBinPath sets the path to the dcraw-json binary.
func SetDCRawBinPath(newBinPath string) {
binPath = newBinPath
}
// GetImageData calls the dcraw-json binary and returns it's output as RawDat... |
package util
import (
"sync"
"time"
)
type Cache struct {
TTL uint
cache map[string]cacheResult
mutex sync.Mutex
}
type cacheResult struct {
value interface{}
err error
time time.Time
}
func NewCache(ttlSeconds uint) *Cache {
return &Cache{
TTL: ttlSeconds,
cache: make(map[string]cacheResult),
}... |
package main
import (
"fmt"
"log"
"os"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"strings"
)
func connect() (session *mgo.Session) {
connectURL := "localhost"
session, err := mgo.Dial(connectURL)
if err != nil {
fmt.Printf("Can't connect to mongo, go error %v\n", err)
... |
package main
import (
"context"
"fmt"
"log"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"gi... |
package gorasp
import (
"errors"
)
type RankSelectSimple struct {
array []int
}
func (self *RankSelectSimple) At(index int) int {
if index >= len(self.array) {
return 0
}
return self.array[index]
}
func NewRankSelectSimple(array []int) *RankSelectSimple {
obj := new(RankSelectSimple)
obj.array = array
ret... |
package storage
import (
"github.com/globalsign/mgo"
log "github.com/sirupsen/logrus"
)
// Session stores mongo session
var session *mgo.Session
// Session is the interface for a docktor session
type Session interface {
SetMode(consistency mgo.Mode, refresh bool)
Close()
}
//Client is the entrypoint of Docktor ... |
package admin
import (
"fmt"
"net/url"
"bytes"
"encoding/base64"
"encoding/json"
"net/http"
"io/ioutil"
"github.com/danielsomerfield/authful/common/wire"
"crypto/x509"
"crypto/tls"
)
type ClientRegistration struct {
Data struct {
ClientId string `json:"clientId,omitempty"`
ClientSecret string `json... |
package main
import(
"manager"
"manager/nsmanager"
"fmt"
"time"
"flag"
)
func main(){
start := time.Now()
t := flag.String("t", "ns", "nation stat data type")
flag.Parse()
var m manager.Manager
switch *t {
case "ns":
m = nsmanager.NewNationStatMa... |
package e
type Err interface {
Code() int
Error() string
}
type BaseErr struct {
C int
E string
}
func (e *BaseErr) Code() int {
return e.C
}
func (e *BaseErr) Error() string {
return e.E
}
func New(code int, msg string) Err {
return &BaseErr{code, msg}
}
func NewInnerErr(msg string... |
package model
import "testing"
func TestMove(t *testing.T) {
r := Room{}
r.TablePieces.P1 = &TablePiecesOne{
Pieces: Pieces{
"1-1": 1,
"1-2": 1,
},
Die: nil,
}
r.TablePieces.P2 = &TablePiecesOne{
Pieces: Pieces{
"1-0": 1,
"1-3": 1,
},
Die: nil,
}
f, err := r.TablePieces.Move("p1", "1-1",... |
package main
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
var (
ErrInvalidDate = errors.New("Invalid date")
ErrInvalidYear = errors.New("Invalid year")
ErrInvalidMonth = errors.New("Invalid month")
ErrInvalidDay = errors.New("Invalid day")
)
type BusinessHours struct {
Start int32
End int32
... |
package routes
import (
"encoding/json"
"net/http"
"fmt"
"io/ioutil"
"github.com/gorilla/mux"
"github.com/YaminLi/jukebox/models"
)
func addSongRoutes(r *mux.Router) {
// r.PathPrefix("/web/").Handler(http.StripPrefix("/web/", http.FileServer(http.Dir("web/"))))
r.HandleFunc("/", homeHandler)
r.H... |
/*
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, so... |
package models
import (
"encoding/json"
validator "gopkg.in/validator.v2"
)
// Role data model.
type Role struct {
Model
Name string `gorm:"not null;unique" validate:"min=3,max=25" json:"name"`
}
// Validate a role.
func (r *Role) Validate() error {
return validator.Validate(r)
}
// NewRole creates a new role... |
package firewall
import (
"os/exec"
"strconv"
)
var (
// iptablesCmd is the iptables bin location.
iptablesCmd = "/sbin/iptables"
)
// Execer is implemented by any values that has a Exec() method. The Exec method
// is used to run a command return the output or an error.
type Execer interface {
Exec() ([]byte, ... |
package configs
import (
"fmt"
"log"
"os"
"strings"
"github.com/spf13/viper"
)
// InitConfig initialize database connection and return the connection object
func InitConfig(filename string) {
if err := setEnv(filename); err != nil {
log.Printf("Error loading config: %s", err.Error())
panic("Failed to load... |
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 ... |
/*
Copyright 2021 RadonDB.
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
distri... |
package employees
import (
"github.com/jakewitcher/pos-server/graph/model"
"strconv"
)
type Role string
const (
Manager Role = "MANAGER"
SalesAssociate Role = "SALES_ASSOCIATE"
)
type EmployeeEntity struct {
Id int64 `json:"id"`
StoreId int64 `json:"store_id"`
FirstName string `json:"first_... |
// ˅
package main
// ˄
type State interface {
// Set time
SetTime(context Context, hour int)
// Use a safe
UseSafe(context Context)
// Sound a emergency bell
SoundBell(context Context)
// Make a normal call
Call(context Context)
ToString() string
// ˅
// ˄
}
// ˅
// ˄
|
package main
import "fmt"
func Solution(str string) []string {
var strSlice []string
letters := ""
for i, x := range str {
if len(letters) <= 2 {
letters += string(x)
fmt.Println(letters)
}
if len(letters) == 2 {
strSlice = append(strSlice, letters)
//fmt.Println(letters)
letters = ""
}
... |
package main
import (
"flag"
"os"
"time"
"github.com/DavidHuie/n2s/n2s"
)
func main() {
source := flag.String("source", "/var/log/nginx/access.log", "the NGINX source file to process")
dest := flag.String("dest", "/var/log/stats.log", "the destination file in which to write the statsd summary")
duration := fl... |
package storewatch_test
import (
"context"
"fmt"
"testing"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/tidb/br/pkg/conn/util"
"github.com/pingcap/tidb/br/pkg/utils/storewatch"
"github.com/stretchr/testify/require"
pd "github.com/tikv/pd/client"
)
type SequentialReturningStoreMeta struct {
se... |
package index
func validateAddQuiz(quiz Quizzes) map[string]interface{} {
finalError := make(map[string]interface{})
if len(quiz.Question) < 4 {
finalError["Question"] = "Length of question must be greater than 4"
}
if len(quiz.Answer) == 0 {
finalError["Answer"] = "Can't submit an empty answer"
}
if len(qu... |
package main
type TemperatureSensor struct {
Estimator
temperature int
}
func MakeTemperatureSensor() *TemperatureSensor {
return &TemperatureSensor{
temperature: 0,
}
}
func (sensor *TemperatureSensor) Get() int {
return sensor.temperature
}
|
package main
import (
"time"
)
// 模型定义、约定、标签、自动迁移和迁移接口
// 模型定义
type Student struct {
ID uint
Name string
Age uint
Email string
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt time.Time
}
/**
约定:默认情况下,GORM 约定使用 ID 作为主键,使用结构体名的复数作为表名,字段名作为列名,使用 CreatedAt、UpdatedAt、DeletedAt时间追踪。
当然,你可以... |
package cli
import (
"github.com/kohirens/tmpltoapp/internal/test"
"os"
"strings"
"testing"
)
func TestGetTmplLocation(runner *testing.T) {
fixtures := []struct {
name, want string
cfg *Config
}{
{"relative", "local", &Config{TmplPath: "./"}},
{"relative2", "local", &Config{TmplPath: "."}},
{"r... |
package conv
import "time"
type Person struct {
num int
haveName bool
haveEmail bool
haveBeer bool
startName time.Time
doneName time.Time
startEmail time.Time
doneEmail time.Time
startBeer time.Time
doneBeer time.Time
name string
email string
beer string
}
type Queue struct {
q []... |
// Copyright 2015 Alexey Martseniuk. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.
package linq
import (
"container/list"
"testing"
)
func BenchmarkChan(b *testing.B) {
ch := make(chan T)
go func() {
for i := 0; i < b.N; i++ {
ch <- i
... |
package server
import (
"go-binar/response"
"go-binar/user/domain"
"go-binar/user/domainservice"
"go-binar/user/repository"
"go-binar/user/repository/sqlite"
"net/http"
"time"
"github.com/labstack/echo"
"github.com/jmoiron/sqlx"
)
type Server struct {
UserRepo repository.UserRepository
UserService dom... |
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
)
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
regex := regexp.MustCompile(`v(\d+)\.(\d+)\.(\d+)(?:-(\d+))?`)
matches := regex.FindStringSubmatch(os.Args[1])
major := matches[1]
minor := matches[2]
pat... |
// Copyright 2016-2021, Pulumi Corporation.
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/hashicorp/hcl/v2"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-aws-native/provider/pkg/cf2pulumi"
pschema "github.com/pulumi/pulumi-aws-native/pro... |
package bbox
import (
"fmt"
"github.com/nsf/termbox-go"
)
const (
TICK_DELAY = 2
)
type Render struct {
beats Beats
closing chan struct{}
msgs <-chan Beats
tick int
ticks <-chan int
iv Interval
intervalCh <-chan Interval
}
func InitRender(msgs <-chan Beats, ticks <-chan int, intervalCh... |
package routes
import (
"assignment_2/configs"
"assignment_2/controllers"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
func ApiRoute(e *echo.Echo, db *gorm.DB) {
// Initialize base controller
redis := configs.GetRedis()
redisDb := configs.GetRedisDb()
base := controllers.Controller{Db: db, Redis: redis, Red... |
package awssqs
import (
"context"
"encoding/json"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"... |
package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
)
const (
SOCK = "/var/run/appgo.sock"
)
type Server struct {
Type string
}
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body := "Hello World " + s.Type + "\n"
fmt.Fprint(w, body)
}
func main() {
sigcha... |
package rules
import (
"fmt"
"github.com/bonjourmalware/melody/internal/events"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"os"
)
var (
assetsBasePath string
)
func init() {
assetsBasePath = "test_resources"
}
// ReadRawTCPPacketsFromPcap is an helper ... |
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// Likes represents a row from 'sun.likes'.
// M... |
/*
* @lc app=leetcode.cn id=64 lang=golang
*
* [64] 最小路径和
*/
// @lc code=start
package main
import "fmt"
func main() {
a := [][]int{
{1,3,1},
{1,5,1},
{4,2,1},
}
fmt.Println(minPathSum(a))
}
func minPathSum(grid [][]int) int {
n := len(grid)
m := len(grid[0])
states := make([][]int, n)
for i ... |
package utils
import (
"testing"
)
func TestNew (t *testing.T) {
{
trackA, er := New(1, "artist_a", "album_a", "track_a")
if er != nil || trackA.TrackId != 1 || trackA.Artist != "artist_a" || trackA.Album != "album_a" || trackA.TrackName != "track_a" {
t.Errorf("Wronng Track created")
}
}
{
trackAA, e... |
package sgorm
import "gorm.io/gorm"
type oRepository struct {
db *gorm.DB
}
|
//Package lists contains custom doubly linked lists that allow for fast insertion and deletion of elements
package lists
import "net"
//Type ConnList represents a list of client connections to a server
type ConnList struct {
Head, Tail *Node //head and tail nodes, necessary for the list
Size int //size of t... |
package repository
import "database/sql"
type TaskAdditionalField struct {
TaskUUID string `json:"-"`
Key string `json:"key"`
Value string `json:"value"`
}
func InsertTaskAdditionalField(db *sql.DB, taskAdditionalField *TaskAdditionalField) (err error) {
var taskUUID, key string
res := db.QueryRow(
"S... |
package main
import (
"fmt"
"os"
"strings"
"github.com/abrander/go-supervisord"
"github.com/sensu-community/sensu-plugin-sdk/sensu"
"github.com/sensu/sensu-go/types"
)
// Config represents the check plugin config.
type Config struct {
sensu.PluginConfig
Host string
Port int
Socket string
Critica... |
package component
/**
*
* Create BY YooDing
*
* Des: maven
*
* Time: 2019/7/6 3:03 PM.
*
* <a href="https://github.com/YooDing/gone">Github</a>
*/
|
package main
import (
"github.com/jjeffery/stomp"
)
func main() {
// send with receipt and an optional header
err := c.Send(
"/queue/test-1", // destination
"text/plain", // content-type
[]byte("Message number 1"), // body
stomp.NewHeader("expires", "2020-12-31 23:59:59"))
if err ... |
package mt
import (
"fmt"
"io"
"reflect"
)
type Inv []NamedInvList
type NamedInvList struct {
Name string
InvList
}
func (inv Inv) List(name string) *NamedInvList {
for i, l := range inv {
if l.Name == name {
return &inv[i]
}
}
return nil
}
func (i Inv) Serialize(w io.Writer) error {
return i.Seria... |
package main
import (
"crypto/md5"
"encoding/json"
"flag"
"fmt"
"github.com/boltdb/bolt"
"html/template"
"io"
"log"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
const (
BucketName = "domains"
TimeFormat = "2006-01-02 15:04:05"
)
var port string
var workingPath string
var zonePath string
type ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//91. Decode Ways
//A message containing letters from A-Z is being encoded to numbers using the following mapping:
//'A' -> 1
//'B' -> 2
//...
//'Z' ->... |
package main
import (
"github.com/gin-gonic/gin"
"github.com/lucasvmiguel/goauth"
)
func main() {
router := gin.Default()
router.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
c.Header("Access-Control-Allow-Headers"... |
/*
Go Language Raspberry Pi Interface
(c) Copyright David Thorpe 2016-2018
All Rights Reserved
Documentation http://djthorpe.github.io/gopi/
For Licensing and Usage information, please see LICENSE.md
*/
package sensordb
import (
"fmt"
"regexp"
"strconv"
"time"
)
var (
regexp_key = regexp.MustCompile("^... |
package utils
func CombineDatetime(y string, m string, d string) string {
str := y + "-"
if len(m) == 1 {
str += "0"
}
str += m + "-"
if len(d) == 1 {
str += "0"
}
str += d
return str
}
|
package 字符串
// longestPalindrome1 最长回文。 (朴素版)
func longestPalindrome2(s string) string {
maxLength := 0
result := ""
dp := [1000][1000]int{}
for i := len(s) - 1; i >= 0; i-- {
for t := i; t <= len(s)-1; t++ {
length := t - i + 1
if length == 1 {
dp[i][t] = 1
} else if length == 2 {
if s[i] == s[... |
package bmcrypto
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"github.com/stretchr/testify/assert"
"math/big"
"testing"
)
var TestKeySet1 = []string{
"rsa MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC57qC/BeoYcM6ijazuaCdJkbT8pvPpFEDVzf9ZQ9axswXU3mywSOaR3wflriSjmvRfUNs/BAjshgtJqgviUXx7lE5aG9mcUyvomyFFpfCR2l2... |
package admin
import (
"firstProject/app/http/result"
"firstProject/app/models"
"firstProject/database"
"strconv"
"github.com/gin-gonic/gin"
)
func GoodsList(c *gin.Context) {
returnData := result.NewResult(c)
page, _ := strconv.Atoi(c.Query("page"))
limit, _ := strconv.Atoi(c.Query("limit"))
goods := make... |
package models
import "time"
type Committed struct {
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at" xorm:"created"`
UpdatedBy string `json:"updated_by"`
UpdatedAt time.Time `json:"updated_at" xorm:"updated"`
}
func (Committed) newCommitted(userName string) Committed {
return C... |
package gans
import (
"errors"
"math/rand"
"github.com/unixpickle/autofunc"
"github.com/unixpickle/num-analysis/linalg"
"github.com/unixpickle/serializer"
"github.com/unixpickle/sgd"
"github.com/unixpickle/weakai/neuralnet"
)
func init() {
var f FM
serializer.RegisterTypedDeserializer(f.SerializerType(), De... |
package four
import (
"fmt"
"os"
"strings"
)
func RunDay(filename string, part string) {
file, _ := os.ReadFile("four/" + filename + ".txt")
lines := strings.Split(string(file), "\n")
parts := make(map[string]func(lines []string))
parts["one"] = partOne
parts["two"] = partOne
parts[part](lines)
}
func par... |
package reader
import (
"encoding/base64"
dpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/encoding"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/pb"
"github.com/batchcorp/plumbe... |
package main
import (
"golang/helper"
"testing"
)
func TestMatrix01(t *testing.T) {
input := [][]int{{0, 0, 0}, {0, 1, 0}, {1, 1, 1}}
helper.AssertIntArr2d(updateMatrix(input), [][]int{{0, 0, 0}, {0, 1, 0}, {1, 2, 1}}, t)
}
|
package main
import (
"fmt"
"github.com/DrSmithFr/go-webassembly/src/browser"
"github.com/DrSmithFr/go-webassembly/src/wolfenstein"
"github.com/llgcode/draw2d/draw2dimg"
"github.com/llgcode/draw2d/draw2dkit"
"image/color"
"math"
"runtime"
"syscall/js"
)
var DOM *browser.DOM
var cvs *browser.Canvas2d
var gs *... |
package main
import (
"fmt"
"math"
)
func test1() {
l := []int{100, 300, 23, 11, 2, 4, 6, 4}
MIN := 10000
for i := 0; i < len(l); i++ {
if l[i] < MIN {
MIN = l[i]
}
}
fmt.Println(MIN)
M := 10000
for _, v := range l {
if v < M {
M = v
}
}
fmt.Println(M)
m := 10000
for _, v := range l {
m ... |
package main
// https://gist.github.com/rms1000watt/308ce7e525ebbf5981275981fa002a94
import (
"fmt"
"os"
"text/template"
)
type Person struct {
Name string
Age int
}
type School struct {
Students []Person
Name string
}
func main() {
templateStr := `Hello World:
My Name is: {{.Name}}
My Age is: {{.Age}... |
package main
import (
"fmt"
"math"
"math/rand"
"strconv"
"testing"
"github.com/askiada/GraphDensityCut/model"
"github.com/askiada/GraphDensityCut/session"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
func AddEdge(gr []*model.Node, from, to int) []*model.Node {
fromIdx := from... |
package main
import "testing"
func TestFit1(t *testing.T) {
c := crate{25, 18, 1}
b := box{6, 5, 1}
if fit1(c, b) != 12 {
t.Errorf("test fit1 failed")
}
c = crate{10, 10, 1}
b = box{1, 1, 1}
if fit1(c, b) != 100 {
t.Errorf("test fit1 failed")
}
c = crate{5, 5, 1}
b = box{1, 100, 1}
if fit1(c, b) != 0... |
package auth
import (
"fmt"
"github.com/imsilence/gocmdb/server/controllers/base"
"github.com/imsilence/gocmdb/server/models"
)
type LoginRequiredController struct {
base.BaseController
User *models.User
}
func (c *LoginRequiredController) Prepare() {
c.BaseController.Prepare()
if user := DefaultManager.IsLo... |
package primitives
import (
"encoding/xml"
)
//GradientType is a type to encode XSD ST_GradientType
type GradientType byte
//GradientType maps for marshal/unmarshal process
var (
ToGradientType map[string]GradientType
FromGradientType map[GradientType]string
)
func (t GradientType) String() string {
return Fr... |
package middleware
// HOFSTADTER_BELOW
|
package wif
import (
// Stdlib
"encoding/hex"
mr "math/rand"
"testing"
"time"
"github.com/weibocom/steem-rpc/encoding/wif"
)
type testData struct {
WIF string
PrivateKeyHex string
}
var TestData = []testData{
{
WIF: "5JWHY5DxTF6qN5grTtChDCYBmWHfY9zaSsw4CxEKN5eZpH9iBma",
PrivateKeyH... |
package api
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
//NewGame starts a new game by the first player
func NewGame(w http.ResponseWriter , r *http.Request) {
}
//JoinGame starts a new game by the first player
func JoinGame(w http.ResponseWriter , r *http.Request) {
vars := mux.Vars(r)
w.Wri... |
package api
import (
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/hirondelle-app/api/container"
"github.com/hirondelle-app/api/tweets"
)
type TweetsHandlers struct {
Manager interface {
GetAllTweets() ([]tweets.Tweet, error)
GetTweetByID(tweetID int) (tweets.Tweet, erro... |
package logger
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
contextName = "api"
eventKey = "event"
eventCodeKey = "event_code"
dataKey = "data"
contextKey = "context"
sourceKey = "source_location"
)
func EventField(e string) zapcore.Field {
return zap.String(eventKey, e)
}
... |
package main
import (
"fmt"
)
// 1) A função original não compila pois 150 não está dentro do range da int8
// 2) O próprio erro diz "150 overflows int8" - ou seja, ultrapassa o range de -128 até 127
// 3) Para consertar, necessitamos ou remover a atribuição int8 ou trocar outra que
// comporte o valor
func main() ... |
/*
Copyright 2021. The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writ... |
package k8sml
import (
"gopkg.in/yaml.v3"
"reflect"
"strings"
terraform "KubeArch/kubearch/proletarian/terraform"
)
type Egress struct {
ID string
FromPort string
ToPort string
Protocol string
Cidr []string
RuntimeVariables map[string]string
VirtualFirewall VirtualFirewall
}
type tmpEgress struct {
ID st... |
package service
import (
"context"
"time"
)
// Service load
type Service struct{}
// Handler to requests
func (s *Service) Handler(ctx context.Context, requestUUID string) (err error) {
var timeout time.Duration
for _, s := range requestUUID {
timeout += time.Duration(s)
}
time.Sleep(timeout * time.Milliseco... |
package main
import "fmt"
type FF func(int, int)
type A interface {
F(int, int)
}
type St struct {
Mem string
Point FF
}
func de_func(int, int) {
fmt.Println("success")
}
func (s *St) init_in() {
s.Point = de_func
}
func main() {
var s St
s.init_in()
c := s.Point
c(1, 2)
}
|
package wallet
import (
"strings"
"pmdgo/conf"
"math/big"
)
func (s *service) GetCoinCfg(coin string) (isSupply bool,cfg *conf.Token){
for _,v := range s.walletCfg.Token {
coin = strings.ToLower(coin)
if v.Name == coin {
return true,v
}
}
return false,nil
}
func FloatToBigInt(val float64) *big.Int {
... |
package model
import (
"testing"
"time"
cst "github.com/pedromss/kafli/config/constants"
)
func TestSetRate(t *testing.T) {
oneSec, _ := time.ParseDuration("1s")
var tests = []struct {
rate Rate
valueToSet string
expectedDuration int64
}{
{rate: Rate{&oneSec}, valueToSet: "", expected... |
package user
import (
"context"
"strings"
google_protobuf2 "github.com/gogo/protobuf/types"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
proto "github.com/weisd/web-kit/api/protobuf/user"
_ "github.com/go-sql-driver/mysql"
"github.com/weisd/web-kit/internal/pkg/ierrors"
"github.com/weisd/web-kit/interna... |
package main
import "fmt"
func main() {
switch {
case false:
fmt.Println("This line will not print out!")
case true:
fmt.Println("But this one will be printed out")
}
}
|
package f3
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
url string = "localhost"
parameters HTTPParams = HTTPParams{
"param1": "val1",
"param2": "val2",
}
)
func TestTimeToRFC1123(t *testing.T) {
now, err := time.Parse(time.RFC82... |
package html
import (
"fmt"
"github.com/elliotchance/gedcom"
"github.com/elliotchance/gedcom/html/core"
"io"
)
// IndividualButton is a large coloured button that links to an individuals
// page. It contains the same and some date information. This is also used to
// represent unknown or missing individuals.
type... |
package sessao
import (
"api/factory"
"api/middleware"
"encoding/json"
"net/http"
"os"
"time"
_ "github.com/lib/pq"
"golang.org/x/crypto/bcrypt"
)
func Auth(response http.ResponseWriter, request *http.Request) {
usuarioRequest, err := middleware.NewFromJson(request.Body)
var usuario middleware.Usuario
var... |
package exasol_test
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
"testing"
"time"
"github.com/exasol/exasol-driver-go"
"github.com/stretchr/testify/suite"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
type IntegrationTestSuite struct {
suit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.