text stringlengths 11 4.05M |
|---|
package aoc2015
import (
"testing"
aoc "github.com/janreggie/aoc/internal"
"github.com/stretchr/testify/assert"
)
func TestDay06(t *testing.T) {
assert := assert.New(t)
testCases := []aoc.TestCase{
{Input: "toggle 936,774 through 937,775\n" + // ans1 += 4; ans2 += 8
"turn off 116,843 through 533,934\n" + /... |
package demo1
import "time"
type Cache interface {
Get(url string) (string, bool)
Put(url string, body string)
}
type item struct {
body string
timestamp time.Time
}
// newLRUCache returns a cache with given size.
// "size" is the number of items that could be stored in the cache.
// If more item is added,... |
package sqly
import "errors"
// errors
var (
// ErrQueryFmt sql statement format error
ErrQueryFmt = errors.New("query can't be formatted")
// ErrArgType sql statement format type error
ErrArgType = errors.New("invalid variable type for argument")
// ErrStatement sql syntax error
ErrStatement = errors.New("sq... |
package main
import (
"github.com/dearcj/golangproj/bitmask"
pb "github.com/dearcj/golangproj/network"
"go.uber.org/zap"
"math/rand"
"time"
"unsafe"
)
type DelayedCall struct {
param unsafe.Pointer
function func(unsafe.Pointer)
duration time.Duration
startTime time.Time
}
type ActorF struct {
run ... |
package main
import (
"net/http"
"fmt"
"github.com/acidlemon/rocket"
)
type WebApi struct {
rocket.WebApp
cfg *Config
}
func NewWebApi(cfg *Config) *WebApi {
app := &WebApi{}
app.Init()
app.cfg = cfg
view := &rocket.View{
BasicTemplates: []string{"html/layout.html"},
}
app.AddRoute("/", app.List, v... |
package pathfileops
import (
"fmt"
"strings"
"testing"
"time"
)
func TestFileMgrCollection_AddFileMgrCollection_01(t *testing.T) {
var fileNameExt string
fMgrs1 := FileMgrCollection{}
for i := 0; i < 10; i++ {
fileNameExt = fmt.Sprintf("testAddFile_%03d.txt", i+1)
fmgr, err := fileMgrCollect... |
package main
import "fmt"
func SuperDescriber(i interface{}) {
fmt.Printf("Type is %T and value %v\n", i, i)
}
func main() {
str := "Hello world!"
SuperDescriber(str)
intValue := 22
SuperDescriber(intValue)
std := struct {
name string
}{
name: "Bob",
}
SuperDescriber(std)
}
|
package migrations
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/tespo/satya/v2/db"
"github.com/tespo/satya/v2/types"
)
//
// Migrate runs all migrations
//
func Migrate() {
db, err := db.Open()
if err != nil {
fmt.Print(err)
}
defer db.Close()
// Tables
// create primary tables such as Account, Di... |
package database
import (
"go-admin/config"
"go-admin/global"
"gorm.io/driver/mysql"
_ "gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
)
var DB *gorm.DB
func InitMySQL(admin config.MySQL) {
if db, err := gorm.Open(mysql.Open(admin.Username+":"+admin.Password+"@("+admin.Path+")/"+admin.DBName+"?"+admin.Config), &g... |
package mock
import (
"context"
"time"
"github.com/bobrovka/calendar/internal/models"
"github.com/stretchr/testify/mock"
)
// StorageMock мок хранилища
type StorageMock struct {
mock.Mock
}
// ListEvents мокирует метод
func (m *StorageMock) ListEvents(ctx context.Context, user string, from, to time.Time) ([]*m... |
// Copyright 2018 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package main
import "fmt"
func main() {
var i [5]int = [5]int{1, 2, 3, 4, 5}
var slicedI []int = i[1:3]
fmt.Println("slicedI = ", slicedI)
fmt.Println("i = ", i)
slicedI = []int{7, 8}
fmt.Println("slicedI = ", slicedI)
fmt.Println("i = ", i)
}
|
// Template Declare Start
//
// ${function_name}:${todo}
// @Description:${todo}
// @receiver ${receiver}
// @param ${params}
// @return ${return_types}
//
// Template Declare End
// Methods Declare
//
// Method1:
// @Description:
//
func Method1() {
} |
package linkaja
type PublicTokenRequest struct {
TrxId string
Total string
SuccessUrl string
FailedUrl string
Items []PublicTokenItemRequest
MSISDN string
DefaultLanguage string
DefaultTemplate string
}
type PublicTokenItemRequest struct {
Name string
Pr... |
package kafka
import (
"encoding/json"
ckafka "github.com/confluentinc/confluent-kafka-go/kafka"
route2 "github/cassiolpaixao/simulator-go/application/route"
"github/cassiolpaixao/simulator-go/infra/kafka"
"log"
"os"
"time"
)
func Produce(msg *ckafka.Message){
producer := kafka.NewKafkaProducer()
route := ro... |
package main
import (
"github.com/flix-tech/k8s-mdns/mdns"
"log"
"k8s.io/client-go/kubernetes"
"k8s.io/api/core/v1"
"fmt"
"flag"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/apimachinery/pkg/watch"
"net"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func mustPublish(rr string) {
if err := mdns.Publish(rr);... |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Hello, Andrei :-)")
var a int
start:
fmt.Print("1. Calculate area of a rectangle. " +
"\n2. Calculate length and diameter of a circle by area." +
"\n3. Expand three-digit number into hundreds, tens, units." +
"\n9. For exit." +
"\nChoose pr... |
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
const (
// Up is the north direction in the grid.
Up = iota
// Right is the east direction in the grid.
Right
// Down is the south direction in the grid.
Down
// Left is the west direction in the grid.
Left
)
// Step represent a... |
package main
import (
"net/http"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
)
type Hosts map[string]http.Handler
func (h Hosts) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if handler := h[r.Host]; handler != nil {
handler.ServeHTTP(w, r)
} else {
http.Error(w, http.StatusTe... |
package sync
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"k8s.io/client-go/util/workqueue"
)
func TestNoParallelismSamePriority(t *testing.T) {
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
throttler := NewThrottler(0, queue)
throttler.Add("c", 0, time.... |
package components
import (
"context"
"github.com/mitchellh/go-glint"
)
func WatchEvent(isRunning bool, message glint.Component, yield []glint.Component) *WatchEventComponent {
return &WatchEventComponent{isRunning: isRunning, message: message, yield: yield}
}
func LargeEvent(message glint.Component, yield []... |
package easy771
func numJewelsInStones(jewels string, stones string) int {
set := make(map[rune]struct{})
for _, v := range jewels {
set[v] = struct{}{}
}
var cnt int
for _, v := range stones {
if _, ok := set[v]; ok {
cnt++
}
}
return cnt
}
|
// Copyright 2018 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 in ... |
/*
* @lc app=leetcode.cn id=942 lang=golang
*
* [942] 增减字符串匹配
*/
package main
// @lc code=start
func diStringMatch(s string) []int {
ret := make([]int, len(s)+1)
start := 0
end := len(s)
for i := 0; i < len(s); i++ {
if s[i] == 'I' {
ret[i] = start
start++
} else {
ret[i] = end
end--
}
}
if... |
package resources
import (
"errors"
"net/http"
"github.com/manyminds/api2go"
"gopkg.in/mgo.v2/bson"
"themis/utils"
"themis/models"
"themis/database"
)
// AreaResource for api2go routes.
type AreaResource struct {
AreaStorage *database.AreaStorage
WorkItemStorage *database.WorkItemStorage
}
func (c AreaRes... |
// test-quickSort project doc.go
/*
test-quickSort document
*/
package main
|
package main
import (
"fmt"
)
func main() {
i := 2
switch i {
case 1, 2, 3:
fmt.Println("one, two, three")
default:
fmt.Println("something else")
}
}
|
// Copyright 2020, Homin Lee <homin.lee@suapapa.net>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"time"
"github.com/suapapa/go_devices/max7219"
"periph.io/x/conn/v3/spi/spireg"
"periph.io/x/host/v3"
)
func ma... |
package example
import (
"time"
"github.com/asaskevich/govalidator"
)
type ExampleModel struct {
ID int `db:"id"`
Title string `db:"title" valid:"required"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
func (t *ExampleModel) Validate() error {
_, err := govalidator.... |
package util
import(
"time"
//"fmt"
)
const DateFormat = "2006-01-02"
var DefaultDate time.Time = time.Time{}
var Days = [13]int{-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
//the @label is like yyyyMM
func ParseDate(label string) time.Time {
t := DefaultDate
if len(label) == 0 {
retu... |
package logging
import (
"fmt"
"log"
"os"
)
type LoggerWrapper struct {
logger *log.Logger
}
var (
Error = &LoggerWrapper{
logger: log.New(os.Stderr, "ERROR ", log.Ldate|log.Ltime|log.Lshortfile),
}
Info = &LoggerWrapper{
logger: log.New(os.Stdout, "INFO ", log.Ldate|log.Ltime|log.Lshortfile),
}
Trace... |
package main
import (
"database/sql"
"fmt"
"github.com/glaslos/ssdeep"
_ "github.com/mattn/go-sqlite3"
"log"
"strconv"
)
var db *sql.DB
const (
DB_PATH = "./data.db"
// hashtypes
HASH_HTML_SSDEEP = 0
HASH_IMAGE_SSDEEP = 1
HASH_EDGES_SSDEEP = 2
HASH_HEADER_SSDEEP = 3
HASH_IMAGE_PHASH = 4
HASH_EDGE... |
package game_map
import (
"github.com/steelx/go-rpg-cgm/state_machine"
)
type CharacterStateBase struct {
Character *Character
Map *GameMap
Entity *Entity
Controller *state_machine.StateMachine
}
type Character struct {
Id string
Anims map[strin... |
// Copyright (c) 2018 John Dewey
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, dist... |
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/signup", signup).Methods("POST")
router.HandleFunc("/login", login).Methods("POST")
router.HandleFunc("/protected", TokenVerifyMiddleWare(protectedEndpoint)).Methods("GET")
lo... |
package main
import "github.com/gin-gonic/gin"
func main() {
// Creates a router without any middleware by default
r := gin.New()
// By default gin.DefaultWriter = os.Stdout
r.Use(gin.Logger())
// Recovery middleware recovers from any panics and writes a 500 if there was one.
r.Use(gin.Recovery())
r.GET("/ping... |
package redis
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func Test(t *testing.T) {
client := Start("localhost:6379")
assert := assert.New(t)
err := client.Connect()
assert.NoError(err)
t.Run("test request,response", func(t *testing.T) {
err := client.Request("SET", "test", "ICE baby")... |
//
// Brian Bulkowski copywrite 2015
//
// I found out that when we built the cheesecave project, we tried to use YAML,
// but the YAML we built was broken. And YAML is far out of favor now.
// We wanted to use YAML because it seemed to have better streaming support.
// json seems to have decent streaming support by ta... |
package dialog
import (
"reflect"
"testing"
)
func TestMakingKeywordsMap(t *testing.T) {
keywords := []string{"a", "b", "c"}
expectedMap := map[string]bool{
"a": true,
"b": true,
"c": true,
}
calculatedMap := makeKeywordsMap(keywords)
if !reflect.DeepEqual(calculatedMap, expectedMap) {
t.Errorf("error... |
/*
File describe main handle structure which includes broker and db connection.
Author: Igor Kuznetsov
Email: me@swe-notes.ru
(c) Copyright by Igor Kuznetsov.
*/
package handlers
import (
"github.com/gorilla/websocket"
"github.com/streadway/amqp"
"simple-tracking/backend/models"
"simple-tracking/backend/utils"
)... |
package services
import (
"time"
"models"
)
var postsDb = []models.Post{}
func Add(content string) (models.Post) {
var newPost = models.Post{
Date: time.Now(),
Content: content,
}
postsDb = append(postsDb, newPost)
return newPost
}
func Get() ([]models.Post) {
return postsDb
} |
package main
import (
"fmt"
"strconv"
"jblee.net/adventofcode2018/utils"
)
func main() {
lines := utils.ReadLinesOrDie("input.txt")
freq := 0
for _, line := range lines {
delta, _ := strconv.Atoi(line)
freq += delta
}
fmt.Printf("freq: %d\n", freq)
}
|
package collection
// StateReference is a reference to a collection state.
type StateReference interface {
// StateNum returns the sequence number of the reference.
StateNum() StateNum
// Create creates a new collection state with the given state number and data.
// If a state already exists with the state number... |
package main
import (
"log"
"time"
"github.com/golang/protobuf/ptypes"
//ptypes "github.com/golang/protobuf/ptypes"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
)
// CreateProtobufTimestamp converts a string to a date then to a protobuf timestamp
func CreateProtobufTimestamp(timeString string) *times... |
package tests
import (
"encoding/json"
"testing"
"github.com/kataras/iris/httptest"
"github.com/iris-contrib/httpexpect"
"../app"
"../config"
)
func InitTestServer(t *testing.T) *httpexpect.Expect {
config.Config.DatabaseDriver = "sqlite3"
config.Config.DatabaseDSN = "./test.db"
app := app.NewApp()
retur... |
package chat
import (
"encoding/json"
"errors"
"log"
"time"
)
type LoginData struct {
Username string `json:"username"`
Password string `json:"password"`
}
type User struct {
Name string `json:"name"`
Id int64 `json:"id"`
Username string `json:"username"`
Token string `json:"token"`
}
func l... |
package context_test
import (
"github.com/APTrust/exchange/context"
"github.com/APTrust/exchange/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"path"
"path/filepath"
"testing"
)
func TestNewContext(t *testing.T) {
configFile := filepath.Join("config", "test.json")
a... |
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"mime"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/stripe/stripe-go"
"golang.org/x/net/context"
"google.golang.org/appengine/log"
"google.golang.org/appengine/urlfetch"
)
type PostmarkMessageHeader struct {
Name stri... |
package voicetext
const (
Show = "show"
Haruka = "haruka"
Hikari = "hikari"
Takeru = "takeru"
)
const (
Happiness = "happiness"
Anger = "anger"
Sadness = "sadness"
)
|
package graphql
import "text/template"
var schemaTemplate = template.Must(template.New("schema").Funcs(funcMap).Parse(`
## !NOTE: This file is auto-generated DO NOT EDIT
## Generated at {{now}}
{{define "field" -}}
{{.Name}}: {{if .Type.IsList}}[{{end -}}
{{.Type.Name}}{{if .Type.NonNullable}}!{{end}}
{{- if .Type.I... |
package main
import (
"flag"
"fmt"
"log"
"os"
"time"
"github.com/teploff/otus/hw_10/client"
"github.com/teploff/otus/hw_10/server"
)
var timeOut = flag.Duration("timeout", 10*time.Second, "reactive power frequency")
func main() {
flag.Parse()
if len(flag.Args()) < 2 {
log.Fatal("not enough cli arguments... |
package config
import (
"github.com/BurntSushi/toml"
)
var App appConfig
var System systemConfig
var Mongo mongoConfig
var Logger logConfig
type TomlConfig struct {
AppConfig appConfig `toml:"app"` // App信息配置
SystemConfig systemConfig `toml:"system"` // 系统设置信息
MongoConfig mongoConfig `toml:"mongo"` /... |
package main
import (
"../SftpPb"
"bufio"
"context"
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
)
type server struct{}
func main() {
fmt.Println("Server was initialized")
lis, err := net.Listen("tcp", "0.0.0.0:50051")
... |
func anagramMappings(A []int, B []int) []int {
bIdx := make(map[int]int)
for i := 0; i < len(B); i++ {
bIdx[B[i]] = i
}
var idxMap []int
for i := 0; i < len(A); i++ {
idxMap = append(idxMap, bIdx[A[i]])
}
return idxMap
} |
package main
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"net/http/cookiejar"
"os"
"sync"
"time"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
Firstname string `json:"firstname"`
Lastname string `json:"lastna... |
package gowebdav
import (
"encoding/base64"
"net/http"
)
// BasicAuth structure holds our credentials
type BasicAuth struct {
user string
pw string
}
// Type identifies the BasicAuthenticator
func (b *BasicAuth) Type() string {
return "BasicAuth"
}
// User holds the BasicAuth username
func (b *BasicAuth) Use... |
package main
import "fmt"
func main() {
test("thisisstring")
test("10")
test(true)
}
func test(a interface{}) {
fmt.Printf("(%v, %T)\n", a, a)
}
###############################################
// new example
package main
import (
"fmt"
)
type Animal interface {
Speak() string
}
type Dog stru... |
// Copyright 2022 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 in wr... |
package hsm
import "reflect"
import "fmt"
// AssertEqual asserts the equality of actual and expected.
func AssertEqual(expected, actual interface{}) {
if !ObjectAreEqual(expected, actual) {
panic(fmt.Sprintf("Equal(%#v, %#v) fail", expected, actual))
}
}
// AssertEqual asserts the inequality of actual and expect... |
package boom
import (
"context"
"go.mercari.io/datastore"
)
// FromContext make new Boom object with specified context.
//
// Deprecated: use FromClient instead.
func FromContext(ctx context.Context) (*Boom, error) {
client, err := datastore.FromContext(ctx)
if err != nil {
return nil, err
}
return &Boom{Con... |
package relay
import (
"fmt"
"github.com/lishimeng/go-libs/log"
"github.com/lishimeng/go-libs/stream/serial"
"io"
"net"
)
type Worker struct {
socks io.ReadWriteCloser
ser io.ReadWriteCloser
server net.Listener
listen uint16
Ser serial.Config
bufSize int
}
func New(serialConf serial.Config, listen u... |
package bca
import "fmt"
type ErrorMessage struct {
Indonesian string `json:"Indonesian"`
English string `json:"English"`
}
type ErrorResponse struct {
ErrorCode string `json:"ErrorCode"`
ErrorMessage ErrorMessage `json:"ErrorMessage"`
}
func (e *ErrorResponse) getMessage() string {
return fmt.Spri... |
/*
Package error provides controllers for various http error codes.
*/
package error
|
package token
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"time"
"gotest.tools/assert"
)
func TestIsTokenValid(t *testing.T) {
assert.Equal(t, false, IsTokenValid(""), "Empty token is declared as valid")
assert.Equal(t, false, IsTokenValid(".."), "Token with three empty parts is declared a... |
package router
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/canmor/go_ms_clean_arch/pkg/adapter/outbound"
"github.com/canmor/go_ms_clean_arch/pkg/adapter/outbound/db"
"github.com/canmor/go_ms_clean_arch/pkg/domain/blog"
"github.com/jarcoal/httpmock"
"github.com/stretchr/testify/assert"
"log"
"ne... |
package database
import "github.com/eliquious/core"
// SignInRequestStore stores all the user requests.
type SignInRequestStore interface {
SignIn(id, secret, csrf string, pubkey []byte) error
}
// NewSignInRequestStore creates a new sign-in request store.
func NewSignInRequestStore(ks core.Keyspace) SignInReque... |
package main
import (
"fmt"
"sync"
)
type WebConfig struct {
Port int
}
var demo *WebConfig
var once sync.Once
func GetConfig() *WebConfig {
//go提供了内置的方法,用来创建单例方法,通过atomic 原子包达到加锁的效果
once.Do(func() {
demo = &WebConfig{Port: 8080}
})
return demo
}
func main() {
c := GetConfig()
c2 := GetConfig()
c.P... |
package armstrong
func power(base, exponent int) int {
if exponent == 0 {
return 1
}
return base * power(base, exponent - 1)
}
func lengthOf(n, base int) int {
count := 0
for n > 0 {
count ++
n /= base
}
return count
}
func IsNumber(n int) bool {
armstrong, length, copy := 0, lengthOf(n, 10), n
for n ... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"gopkg.in/yaml.v2"
)
type Team struct {
Name string `yaml:"name"`
Members []string `yaml:"members"`
Repositories []string `yaml:"repositories"`
}
type Config struct {
Organ... |
package classfile
// ConstantClassInfo
// class_info
/**
Class_info{
tag u1
index u2 指向全限定名常量的索引
}
*/
type ConstantClassInfo struct {
cp ConstantPool // 常量池句柄
nameIndex uint16 //指向全限定名常量的索引
}
func (self *ConstantClassInfo) readInfo(reader *ClassReader) {
self.nameIndex = reader.... |
package main
import (
"github.com/stefanoguerrini/http-beat/cmd"
)
func main() {
cmd.Execute()
}
|
package http
import (
"net/http"
"github.com/gorilla/websocket"
"github.com/julienschmidt/httprouter"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (h *Handler) Upgrade(w http.ResponseWriter, r *http.Reques... |
/*
Package greeting implements a single function that returns a greeting
*/
package greeting
// Return a hello world greeting
func HelloWorld() string {
return "Hello, World!";
}
|
// Copyright 2021 Google LLC
//
// 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 ... |
package main
import (
"fmt"
"os"
"log"
"encoding/csv"
"bufio"
"io"
"github.com/janritter/go-geo-ip/geoip"
"github.com/cheggaaa/pb"
"strconv"
)
type blockedIP struct {
IP string
Country string
Latitude float64
Longitude float64
}
func runBlockLog() {
fmt.Println("Input blockfile filename: ")
filename :... |
// This file was generated for SObject Contract, API Version v43.0 at 2018-07-30 03:47:32.202844694 -0400 EDT m=+18.546147034
package sobjects
import (
"fmt"
"strings"
)
type Contract struct {
BaseSObject
AccountId string `force:",omitempty"`
ActivatedById string `force:",omitempty"`
... |
package net
import (
"Zinx/Project/Zinx/v3-Request/zinx/iface"
"fmt"
"net"
"strings"
)
//定义一个server结构
type Server struct {
IP string
Port uint32
Name string
TCPVersion string
}
//创建Server方法
func NewServer(name string) iface.Iserver { //相当于多态
return &Server{
IP: "0.0.0.0",
Por... |
package main
import (
"fmt"
"os"
"strings"
"time"
)
func main() {
str := "a"
elapsed := time.Now()
for i := 1; i < 10; i++ {
str += str
//fmt.Println(i)
}
//nanosec:=time.Since(elapsed).Nanoseconds()
//fmt.Printf("%d sec", nanosec)
sec := time.Since(elapsed).Seconds()
fmt.Printf("No effective : %.8f ... |
package main
import "fmt"
func main() {
var P, r, Y float64 //may as well to make them compatible easily
fmt.Printf("Enter the principal: £")
fmt.Scanf("%f", &P)
fmt.Printf("Enter the rate of interest: ")
fmt.Scanf("%f", &r)
fmt.Printf("Enter the number of years: ")
fmt.Scanf("%f", &Y)
fmt.Printf("After %... |
package bob
import (
"regexp"
"strings"
)
const testVersion = 2
func Hey(phrase string) string {
greeting := Greeting{phrase: phrase}
if greeting.IsShout() {
return "Whoa, chill out!"
}
if greeting.IsQuestion() {
return "Sure."
}
if greeting.IsSilence() {
return "Fine. Be that way!"
}
return "Whatev... |
package main
func main() {
linkList := &LinkedList{}
linkList.push(10)
linkList.push(20)
linkList.push(30)
linkList.push(40)
linkList.push(50)
linkList.print()
linkList.reverse()
linkList.print()
}
|
package testdata
import (
"github.com/frk/gosql/internal/testdata/common"
)
type UpdateWhereblockBasicSingle1Query struct {
User *common.User4 `rel:"test_user"`
Where struct {
Id int `sql:"id"`
}
}
|
package main
import "fmt"
/**
* author: will fan
* created: 2019/6/30 17:12
* description:
*/
func main() {
var x []int
fmt.Println(x, len(x), cap(x))
x = append(x, 10, 20, 30)
fmt.Println("Slice x:", x)
}
|
// Copyright 2022 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 main
import (
_ "embed"
"os"
"text/template"
)
// START DATA OMIT
var data = struct {
Company string
Employees []string
}{
"Weave",
[]string{"Carson", "Kari", "Tami"},
}
// END DATA OMIT
const templateText = `
{{- "" -}}
-Company Report-
{{- $num := len .Employees }}
{{- $msg := "" }}
{{- if eq $nu... |
package handlers
import (
"encoding/json"
"net/http"
"regexp"
"strconv"
"time"
"github.com/nothingmuch/repricer/errors"
)
// Query constructs a new query price endpoint with the given storage model
func Query(m PriceLogRetriever) http.Handler { return query{m} }
// PriceLogRetriever defines an interface for f... |
package bitcask
import (
"bytes"
"fmt"
"testing"
)
func TestSerialize(t *testing.T) {
r := &record{
tstamp: 20,
key: "name",
value: []byte("李浚"),
}
d, _ := serialize(r)
fmt.Println(len(d))
reader := bytes.NewReader(d)
out, _ := deserializeFrom(reader)
if out == nil {
t.Fail()
}
if out.tstam... |
package models
import (
"github.com/google/cayley"
"strconv"
"time"
)
const (
Iterate15Minutes = 15 * 60
Iterate30Minutes = 30 * 60
Iterate45Minutes = 45 * 60
Wait5Minutes = 5 * 60
)
type User struct {
Name string
iterationTime int64
storage *Storage
}
func NewUser(name string) *User {
use... |
package main
import (
"go-mod/game"
"go-mod/util"
"log"
"github.com/veandco/go-sdl2/sdl"
)
// --
type gameState int
const (
start gameState = iota
play
)
var state = start
// SetStateStart sets the game state to start
func SetStateStart() {
state = start
}
// --
func main() {
err := sdl.Init(sdl.INIT_EV... |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-03 15:50
* Description:
*****************************************************************/
package netstream
import "sync"
type TWaitGroup struct ... |
package task
import (
"github.com/imsilence/gocmdb/agent/gconf"
)
type CatPlugin struct {
}
func (p *CatPlugin) Name() string {
return "cat"
}
func (p *CatPlugin) Init(c gconf.Config) bool {
return true
}
func (p *CatPlugin) Call() (interface{}, error) {
return "cat", nil
}
|
package structHelper
type HelperFunction struct {
ID string `json:"ID"`
Nombre string `json:"nombre"`
Codigo string `json:"codigo"`
Descripcion string `json:"descripcion"`
}
|
// 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 backends
import "fmt"
// DummyAuthorizator is a fake authorizator interface implementation used for test
type DummyAuthorizator struct {
}
// Authorize user for given username and password.
func (a DummyAuthorizator) Authorize(user, pass string) bool {
return true
}
// DummyBackend is a fake backend interf... |
package main
import (
"crypto/sha512"
"database/sql"
"encoding/binary"
"fmt"
"log"
"math"
"net/http"
"os"
"regexp"
"strings"
"time"
_ "github.com/lib/pq"
)
// characters used for short-urls
const (
SYMBOLS = "0123456789abcdefghijklmnopqrsuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ"
BASE = uint32(len(SYMBOLS))
)... |
package plugins
import (
"github.com/dataprism/dataprism-commons/api"
"github.com/dataprism/dataprism-commons/core"
)
type DataprismPlugin interface {
Id() string
CreateRoutes(platform *core.Platform, API *api.Rest)
} |
package order
import (
"github.com/alfuhigi/micro-order-api/pkg/order/item"
"gorm.io/gorm"
)
type Order struct {
gorm.Model
ClientID string
UserID uint
OrderItems []*item.OrderItem
OrderStatus []*OrderStatus
PaymentOptions uint
PickUp string
DropOff string
DeliveryFees ... |
package functions
import (
c "Project/config"
"encoding/json"
"fmt"
"net/http"
"strings"
)
//make json req. with parameters
func ResJSON(name c.Names)(name_json []byte){
n := c.Names{name.Firstname,name.Lastname}
name_json, err := json.Marshal(n)
if err != nil{
ResJSON(EmpytJSON())
}
return
}
//parse GET... |
package entities
import (
discord "github.com/bwmarrin/discordgo"
)
// Player is a Discord player.
type Player struct {
*Character
user *discord.User
}
// NewPlayer create a new player with a given role.
func NewPlayer(role Role, user *discord.User) *Player {
p := Player{
Character: NewCharacter(role),
user... |
package main
import (
"fmt"
)
func add(x int, y int) int {
return x + y
}
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
_, c := swap("hello", "world")
fmt.Println(a, b, c)
var number int
number = 42
if sum := add(number, 13); sum > 50 {
fmt.P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.