text stringlengths 11 4.05M |
|---|
package nrpc
import (
"context"
"github.com/stretchr/testify/require"
"testing"
"time"
)
func TestClient_Call(t *testing.T) {
s := NewServer(ServerOptions{Addr: "127.0.0.1:10087"})
s.Register(&TestService{})
go s.Start(nil)
defer s.Shutdown(context.Background())
time.Sleep(time.Second)
c := NewClient(Clie... |
package main
import (
"encoding/json"
"fmt"
"time"
"reflect"
)
func main() {
Serialize()
Unmarshal()
}
type Student struct {
StuId int `json:"id"`
Name string `json:"name"`
Class string `json:"class"`
RegTime time.Time `json:"reg_time"`
}
func Serialize() {
stu := new(Student)
stu.Stu... |
package timehelper
import (
"fmt"
"reflect"
"testing"
"time"
)
func TestIntAsMonth(t *testing.T) {
type args struct {
month int
}
tests := []struct {
name string
args args
want time.Month
wantErr bool
}{
{name: "1e", args: args{month: 0}, want: month0, wantErr: true},
{name: "2e", args:... |
package parser
import (
"errors"
"fmt"
"reflect"
)
// Parser represents a parser
type Parser struct {
grammar *Rule
errGrammar *Rule
recursionRegister recursionRegister
// MaxRecursionLevel defines the maximum tolerated recursion level.
// The limitation is disabled when MaxRecursionLevel is... |
package imdb
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/jbowtie/gokogiri"
htmlParser "github.com/jbowtie/gokogiri/html"
)
type HttpGetter interface {
Get(url string) (resp *http.Response, err error)
}
type HttpPoster interface {
Post(url string, bodyType string, body io.Reader) (resp *http.Respo... |
// 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 leetcode
import "testing"
func TestRobb(t *testing.T) {
t.Log(robb([]int{1, 2, 3, 1}))
t.Log(robb([]int{2, 7, 9, 3, 1}))
}
|
package fakes
import "errors"
type NoopWriter struct{}
func (no NoopWriter) Write(b []byte) (n int, err error) {
return 0, errors.New("explosions")
}
|
package main
import (
"fmt"
"math/rand"
"time"
)
/*
This is a sample that replicates the try lock pattern using Go.
In this scenario we have two potential callers for the same resource - as specified by the jobFunc() - but only
one of them can access it at any one time. If the resource is in use, then don't wait,... |
package application
import (
"github.com/angryronald/guestlist/internal/guest/application/command"
"github.com/angryronald/guestlist/internal/guest/application/query"
"github.com/angryronald/guestlist/internal/guest/domain/service/guest"
)
type Commands struct {
AddGuest command.AddGuestCommand
GuestArrived ... |
package ora2uml
import (
"database/sql"
"fmt"
"os"
_ "github.com/godror/godror"
)
const (
sqlAllTables = `
select
owner, table_name
from
all_tables
`
)
func readTablesSql(tables []ConfigTable) string {
sql := "select "
sql += "t.owner, t.table_name, c.comments "
sql += "from all_tables t "
sql += "... |
package schedule
import (
"math/rand"
"time"
)
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
// RandomInterval defines a random interval schedule.
type RandomInterval struct {
Interval time.Duration
Randomness float64
}
// EveryRandom takes an interval with an ajustable plus or minus percentage o... |
/*
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... |
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... |
package tests
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"themis/client"
)
var _ = Describe("Space Service", func() {
BeforeEach(func() {
//space = *NewSpace()
})
Describe("Querying Space Service", func() {
Context("With no parameters", func() {
It("shoul... |
package main
import (
"fmt"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
)
func createJWTtoken(login string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"login": login,
"exp": time.Now().AddDate(0, 1, 0).Unix(),
})
tokenString, err := token.SignedString(... |
/*
Copyright 2018 The HAWQ Team.
*/
package internalversion
type MyResourceExpansion interface{}
|
package testutil
import (
"math/rand"
"time"
ci "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto"
)
func RandTestKeyPair(typ, bits int) (ci.PrivKey, ci.PubKey, error) {
return SeededTestKeyPair(typ, bits, time.Now().UnixNano())
}
func SeededTestKeyPair(typ, bits int, seed int64) (ci.Priv... |
package main
import "fmt"
type Shape interface {
Area() int
}
type Square struct {
width int
}
type Rectangle struct {
width int
height int
}
func (s Square) Area() int {
return s.width * s.width
}
func (r Rectangle) Area() int {
return r.width * r.height
}
func recordArea(shape S... |
package data
const (
DB_USER = "user"
DB_PASSWORD = "password"
DB_NAME = "chit"
)
|
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this fi... |
package testutil
import (
"context"
"testing"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
"tagallery.com/api/mongodb"
)
// DropCollection deletes all collections in a MongoDB database.
func DropCollection(db string, collection string) error {
client := mongodb.Client()
_, er... |
package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/elitah/utils/logs"
)
type sqliteTableInfo struct {
name string
sql string
sync bool
cnt int64
}
func SQLiteSync(master, slave *sql.DB, dir string) (int64, error) {
if err := master.Ping(); nil == err ... |
package Account
import (
"context"
"log"
"math/big"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
func GetAddressFromHex(address string) common.Address {
return common.HexToAddress(address)
}
// in wei precision (18 points)
f... |
package memory
import (
"fmt"
"testing"
"github.com/mateeullahmalik/goa-demo/internal/storage"
"github.com/stretchr/testify/assert"
)
// newTestDB. need keep as private method to prevent CI error:
// exported func NewTestDB returns unexported type *memory.keyValue, which can be annoying to use
func newTestDB() *... |
package main
import (
"go_restful/user"
"log"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func initDB() *gorm.DB {
db, err := gorm.Open("mysql", "root@/gorest?parseTime=true")
if err != nil {
log.Fatalln(err)
}
db.AutoMigrate(&user.User{})
return db
}
... |
package util
import (
"errors"
"example.com/selenium/config"
"fmt"
"github.com/tebeka/selenium"
"net"
"os"
)
type Crawler struct {
ChromeDriver string
Port int
Service *selenium.Service
Caps selenium.Capabilities
}
// NewCrawler 开启驱动服务
func NewCrawler() (*Crawler, error) {
port, _ := ... |
// bytes.
package main
import (
"fmt"
)
func main() {
const str = "hello world"
sl := make([]byte, len(str))
sl = []byte(str[:5])
fmt.Printf("sl=%s len=%d\n\n", sl, len(sl))
fmt.Printf("sl[:3]=%s\n", sl[:3])
fmt.Printf("sl[3:]=%s\n\n", sl[3:])
fmt.Printf("len(sl)/2=%d\n", len(sl)/2)
fmt.Printf("sl[:len(sl)... |
package consul
import (
"strings"
consulapi "github.com/hashicorp/consul/api"
)
type ConsulClient struct {
underlying *consulapi.Client
}
type Config struct {
UseSSL bool
Host string
}
func (c ConsulClient) Catalog() *consulapi.Catalog {
return c.underlying.Catalog()
}
func (c ConsulClient) KV() *consulap... |
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type Stack struct {
buffer []*TreeNode
}
func NewStack() *Stack {
return &Stack{make([]*TreeNode, 0)}
}
func (stk *Stack) Push(node *TreeNode) {
stk.buffer = append(stk.buffer, node)
}
func (stk *Stack) Pop() (lastNode *TreeNode) {... |
package models
import (
"time"
)
// Room : roomテーブルモデル
type Room struct {
ID int64
RoomOwner int64
GameTitle int64
Capacity int
IsLock bool
CreatedAt time.Time
}
|
package cloudflare
import (
"context"
"fmt"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
const regionalHostname = "eu.example.com"
func TestListRegions(t *testing.T) {
setup()
defer teardown()
handler := func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet,... |
package singleton
var lazyInstance *LazySingleton
// 单例模式-懒汉式
type LazySingleton struct {
}
func GetLazyInstance() *LazySingleton {
if lazyInstance == nil {
lazyInstance = &LazySingleton{}
}
return lazyInstance
}
|
package output
import "fmt"
//Show prints the values
func Show(array []int) {
fmt.Println(array)
}
|
package db_query_loan
// 证件信息
import (
"bankBigData/BankServerJournal/entity"
"bankBigData/BankServerJournal/table"
"gitee.com/johng/gf/g"
)
func GetUserInfoByIdCard(idCard string) (entity.S_ecif_ecif_cert_info, error) {
db := g.DB()
sql := db.Table(table.SEcifEcifCertInfo).Where(g.Map{"cert_num": idCard})
data... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package twelve
import (
"strings"
)
const testVersion = 1
// Song returns the whole twelve days song.
func Song() string {
return `On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.
On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear T... |
package testutils
import (
"testing"
)
func TestIgnoreKernelVersionCheckWhenEnvVarIsSet(t *testing.T) {
tests := []struct {
name string
toIgnoreNamesEnvValue string
testName string
ignoreKernelVersionCheck bool
}{
{
name: "should NOT ignore ke... |
/*
* @lc app=leetcode.cn id=1137 lang=golang
*
* [1137] 第 N 个泰波那契数
*/
package main
// @lc code=start
var TriList = [38]int{
0,
1,
1,
}
func tribonacci(n int) int {
if n != 0 && TriList[n] == 0 {
TriList[n] = tribonacci(n-3) + tribonacci(n-2) + tribonacci(n-1)
}
return TriList[n]
}
// func main() {
// fmt... |
package handler
import (
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"github.com/google/uuid"
"2019_2_IBAT/pkg/app/auth"
"2019_2_IBAT/pkg/app/auth/session"
"2019_2_IBAT/pkg/app/users"
"2019_2_IBAT/pkg/pkg/config"
. "2019_2_IBAT/pkg/pkg/models"
)
const MAXUPLOADSIZE = 32 * 1024 * 1024 // 1 m... |
// 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 mqtt
import (
"context"
"io/ioutil"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
"github.com/batchcorp/plumber-schemas/build/go... |
package gray_image
import (
"testing"
)
func Test_ResizeProportional(t *testing.T) {
rawFile := "./testdata/big.jpg"
dstFile := "./testdata/out.jpg"
err := ResizeProportional(rawFile, dstFile, 500, 100)
if err != nil {
t.Errorf("resize error: %v", err)
}
}
|
package gfuns
type FFprobe struct {
Streams []struct {
Index int `json:"index"`
CodecName string `json:"codec_name"`
CodecLongName string `json:"codec_long_name"`
Profile string `json:"profile"`
CodecType string `json:"codec_type"`
CodecTimeBase strin... |
package decodestring
func decodeString(s string) string {
numStack := []int{}
strStack := []string{}
var curInt = 0
var t = ""
for i := 0; i < len(s); i++ {
if isNumber(s[i]) {
curInt = curInt*10 + int(s[i]-'0')
} else if s[i] == '[' {
numStack = append(numStack, curInt)
strStack = append(strStack, t... |
// package semver provides a type representing a semantic version, and
// facilities for parsing, serialisation and comparison.
//
// See http://semver.org for more information on semantic versioning.
//
// This package expands on the specification: a partial version string like
// "v2" or "v2.0" is considered valid, a... |
package denvlib
import (
"io/ioutil"
"os"
"reflect"
"testing"
)
func TestIgnore(t *testing.T) {
var d *Denv
d = NewDenv("test-ignore")
err := os.RemoveAll(d.Path + "/*")
check(err)
patterns := []byte(".test\n*.test")
err = ioutil.WriteFile(d.expandPath(Settings.IgnoreFile), patterns, 0644)
d.LoadIgnore()
... |
package fslm
// Basic types and related constants.
import (
"flag"
"fmt"
"io"
"math"
"strconv"
"github.com/kho/word"
)
// StateId represents a language model state.
type StateId uint32
const (
STATE_NIL StateId = ^StateId(0) // An invalid state.
_STATE_EMPTY StateId = 0 // Models always uses s... |
package timbler
import (
"errors"
"time"
logx "github.com/my0sot1s/godef/log"
convt "github.com/my0sot1s/godef/convt"
)
// RoomHub room service
type RoomHub struct {
rooms map[*Room]bool
created int
}
// Init roomHub
func (rh *RoomHub) Init() {
rh.rooms = make(map[*Room]bool)
rh.created = time.Now().Nanos... |
package main
import (
"../config"
"../network/localip"
"fmt"
)
func initializeLiftData() config.Lift {
var lift config.Lift
var requests [config.NumFloors][config.NumButtons]bool
id, err := localip.LocalIP()
if err != nil {
for f := 0; f < config.NumFloors; f++ {
for b := 0; b < config.NumButtons; b++ {
... |
// +build !qml
package album
import (
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/widgets"
"github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/controller"
)
type albumController struct {
widgets.QGroupBox
_ func() `constructor:"init"`
_ *core.QAbstractItemModel `prope... |
package main
import (
"bufio"
"encoding/csv"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
)
type data struct {
points int
sheet map[string]string
}
var (
file *string
duration *int
)
func init() {
file = flag.String("test", "problems.csv", "path to test file")
duration = flag.Int("time", 10, "quiz du... |
package promise
import (
"testing"
)
func Test_Future(t *testing.T) {
source := 1
future := handlerFuture(source)
ch := make(chan interface{})
go future.then(func(response interface{}) (interface{}, error) {
ch <- response
return nil, nil
})
target := <-ch
if target != source {
t.Error("Test_Future F... |
package queue
type QueueArrayImpl struct {
Array []int
}
var _ Queue = &QueueArrayImpl{}
func NewQueue() Queue {
return &QueueArrayImpl{
Array: []int{},
}
}
func (q *QueueArrayImpl) Add(e int) {
q.Array = append(q.Array, e)
}
func (q *QueueArrayImpl) Remove() error {
if len(q.Array) == 0 {
return QueueEmp... |
package main
import "fmt"
func countRemoval(str string, l int, r int, dp [][]int) int{
if l > r || l == r {
return 0
}
if r == l + 1 {
if str[l] == str[r] {
return 0
} else {
return 1
}
}
if dp[l][r] != 0 {
return dp[l][r]
}
var cnt int
if str[l] == str[r] {
cnt = countRemoval(str, l + 1, r... |
package theory
import (
"buddin.us/eolian/dsp"
"buddin.us/musictheory"
lua "github.com/yuin/gopher-lua"
)
func newPitch(state *lua.LState) int {
p, err := musictheory.ParsePitch(state.CheckString(1))
if err != nil {
state.RaiseError("%s", err.Error())
}
state.Push(newPitchUserData(state, *p))
return 1
}
fu... |
package cli
import (
"errors"
"flag"
"os"
"strings"
"github.com/mraraneda/mrlogger"
)
//cli.FlagHandler(&sellerdni, &folio, &order)
// FlagHandler captura los flags declarados y los maneja
func FlagHandler(configfile *string) {
flag.StringVar(configfile, "config", "", "archivo de configuración de la aplicacoi... |
package main
import "fmt"
func main() {
//Map initialization
m := make(map[string]int, 2)
m["k1"] = 7
m["k2"] = 13
m["k3"] = 15
m["k4"] = 17
// fmt.Printf("\nmap:%+v; what is map:%T; \n", m, m)
fmt.Println("m:", m)
delete(m, "k1")
fmt.Printf("\nmap:%+v\n\n", m)
delete(m, "k1")
// m1 := map[string]int{
... |
package check
import (
"github.com/MintegralTech/juno/index"
)
type unmarshal struct {
}
func (u *unmarshal) Unmarshal(idx index.Index, res map[string]interface{}) Checker {
if _, ok := res["check"]; ok {
var checkImpl = &CheckerImpl{}
return checkImpl.Unmarshal(idx, res)
}
if _, ok := res["in_check"]; ok {
... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
const (
resultLines = "*3\r\n$3\r\nSET\r\n$5\r\nprice\r\n$5\r\n99.99\r\n*3\r\n$3\r\nSET\r\n$5\r\ncolor\r\n$3\r\nred\r\n*3\r\n$3\r\nSET\r\n$4\r\nunit\r\n$7\r\nCelsius\r\n"
)
var (
fileSourceLines = []string{
"SET price 99.99",
"SET color ... |
/*
Copyright 2019 The Kubernetes 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, ... |
package rabbitmq
import (
"fmt"
"log"
"github.com/streadway/amqp"
)
const (
//Direct 直行交换机
Direct = "direct"
//Fanout 扇形交换机
Fanout = "fanout"
//Topic 主题交换机
Topic = "topic"
//Headers 首部交换机
Headers = "headers"
//AllUser 所用用户
AllUser = "all"
)
//Connect 测试
type Connect struct {
conn *amqp.Connection ... |
package modules
import (
"errors"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
)
var (
_UserTokenHeaderName = ""
_SecretKeys = ""
_SystemToken = ""
)
type UserMeta struct {
UserID uint
GroupID uint
Token string
}
type CircleCustomClaims struct {
UserID uint
... |
package test_test
import (
. "static_proxy_server/lib/test"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var numberset = []struct {
x int
y int
result int
}{
{1, 2, 3},
{1, 2, 3},
{2, 4, 6},
}
var _ = Describe("Test", func() {
// var book Book
// BeforeEach(func() {
// book = ... |
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package geometry implements several primitive geometry generators.
package geometry
import (
"github.com/hecate-tech/engine/gls"
"github.com/hec... |
package common
import (
"github.com/streadway/amqp"
)
var conn *amqp.Connection
var ch *amqp.Channel
var q amqp.Queue
var config Config
// Closeq closes the queue
func Closeq() {
ch.Close()
conn.Close()
}
// Connq connects to the queue and channel
func Connq() {
var err error
config = LoadConfig()
conn, err =... |
package datastoresql_test
import (
"context"
"fmt"
"math/rand"
"testing"
"time"
"github.com/direktiv/direktiv/pkg/refactor/database"
"github.com/direktiv/direktiv/pkg/refactor/datastore/datastoresql"
"github.com/direktiv/direktiv/pkg/refactor/logengine"
"github.com/google/uuid"
)
func Test_LogStoreAddGet(t ... |
package main
import (
"fmt"
"github.com/raypereda/fibonacci/fib"
)
func main() {
fmt.Println("Hi")
for i := 0; i < 10; i++ {
fmt.Println(i, "fibonacci number is", fib.Fib1(i))
}
} |
package util
import (
crand "crypto/rand"
"encoding/base64"
"encoding/json"
"time"
)
// timeout工具类
func Timeout(ch chan interface{}, timeout time.Duration) (val interface{}, isTimeout bool) {
timeCh := make(chan bool, 1)
go func() {
time.Sleep(timeout)
timeCh <- true
}()
select {
case val := <-ch:
ret... |
package mredis
import (
"sync"
"github.com/garyburd/redigo/redis"
"time"
"strings"
"github.com/2liang/mcache/modules/utils/setting"
)
type RedisOption struct {
Timeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
Db int
MHosts string
SHosts string
}
type BaseRedis struct ... |
// Package bcd provides functions for converting integers to BCD byte array and vice versa.
package bcd
func pow100(power byte) uint64 {
res := uint64(1)
for i := byte(0); i < power; i++ {
res *= 100
}
return res
}
func FromUint(value uint64, size int) []byte {
buf := make([]byte, size)
if value > 0 {
remai... |
package model
//供应商:Supplier
//Id
//供应商编码 SupplierCode
//供应商名称 SupplierName
//供应商id SupplierId foreign key(supplierId) references Order(id) on delete cascade
//联系人 Contact
//联系电话 ContactNumber
//联系地址 ContactAddress
//传真 Fax
//描述 Describe
type Supplier struct {
Id int
SupplierCode string
Supp... |
/*
Copyright 2020 The Kubernetes 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, ... |
package xml
import (
"bufio"
"io"
)
// Reader represents a XML reader.
type Reader struct {
r *bufio.Reader
err error
e Element
n *string
}
// NewReader returns a initialized reader.
func NewReader(r io.Reader) *Reader {
return &Reader{
r: bufio.NewReaderSize(r, 2<<12),
}
}
// Element returns the la... |
package bot
type Update struct {
Messages []*Message
Buttons []*Button
Inlines []*Inline
}
type Button struct {
Text string
Handler Handler
URL string
SwitchInlineQuery string
callbackData string
}
type Message struct {
Text string
}
type Inline struct {
Id s... |
package main
import "fmt"
//定义二维数组,用于保存三个班,每个班五名同学成绩,并求出每个班级平均分、以及所有班级平均分
func main() {
var scores [3][5]float64
for i := 0; i < len(scores); i++ {
for j := 0; j < len(scores[i]); j++ {
fmt.Printf("请输入第%d班,第%d号学生成绩:\n", i+1, j+1)
fmt.Scanln(&scores[i][j])
}
}
totlaSum := 0.0
for i := 0; i < len(scores... |
package console
type Color int
const (
// No change of color
COLOR_DEFAULT Color = iota
COLOR_BLACK
COLOR_RED
COLOR_GREEN
COLOR_YELLOW
COLOR_BLUE
COLOR_MAGENTA
COLOR_CYAN
COLOR_WHITE
)
// Base attributes
const (
Reset Attribute = iota
Bold
Faint
Italic
Underline
BlinkSlow
Bl... |
// 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 wordsearch2
func findFirstLetterIndices(board [][]byte, firstLetter byte) [][]int {
firstLetterIndices := make([][]int, 0)
for indVertical := range board {
for indHorizontal := range board[0] {
if board[indVertical][indHorizontal] == firstLetter {
firstLetterIndices = append(firstLetterIndices, []i... |
package poc
import (
"database/sql"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
)
// BlockingPoc
type BlockingPoc struct {
dbDriverName string
dbDataSourceName string
ChunkSize int
}
// NewBlockingPoc
func NewBlockingPoc(dbDriverName string, dbDataSourceName string, chunkSize int) *BlockingPoc... |
package bot
import (
"net/http"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestConfig(t *testing.T) {
testLogger := noopLogger{}
testHTTPClient := &http.Client{}
var tests = []struct {
name string
opts []Option
want *config
}{
{
name: "logger",
opts: []Option{WithLogger(testLogger)},
wa... |
package main
import (
"strings"
"fmt"
)
// func getUserListSQL(username, email string) string {
// sql := "selsct from user"
// where := []string{}
// if username != ""{
// where = append(where, fmt.Sprintf("username = '%s",username))
// }
// if email != ""{
// where = append(where, fmt.Sprintf("email = ... |
package pov
import (
"errors"
"fmt"
"time"
"github.com/qlcchain/go-qlc/common"
"github.com/qlcchain/go-qlc/common/merkle"
"github.com/qlcchain/go-qlc/common/types"
"github.com/qlcchain/go-qlc/ledger"
"github.com/qlcchain/go-qlc/ledger/process"
"github.com/qlcchain/go-qlc/log"
"github.com/qlcchain/go-qlc/tri... |
// Name of the package is not the directory name
// Package name is what we use in the package declaration
// Directory name is used to find the package location
package display
import "fmt"
// Exported functions as the name is capitalized
func ConsoleLogString(str string) {
fmt.Println(str)
}
func ConsoleLogInt(nu... |
package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
)
func addChannel(client *Client, data interface{}) {
var channel Channel
var message Message
mapstructure.Decode(data, &channel)
fmt.Printf("%#v\n", channel)
channel.ID = "1"
message.Name = "channel add"
message.Data = channel
client.send <- ... |
package command
import (
"fmt"
"os"
"strings"
"text/tabwriter"
pb "github.com/ernestoalejo/tfg-fn/protos"
)
var (
client pb.FnClient
writer = tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
)
func SetClient(c pb.FnClient) {
client = c
}
func FlushOutput() {
writer.Flush()
}
func tabPrint(fields []string... |
package utils
import (
"fmt"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
// EmailData encapsulates email sending data
type EmailData struct {
To []*mail.Email
PageTitle string
Preheader string
Subject string
BodyTitle string
FirstBodyT... |
package main
/*
- scan reads user input
- takes a pointer as an argument
- typed data is written to pointer
- retuns number of scanned items (and the error or nil)
*/
import (
"fmt"
)
func main() {
var n float64
fmt.Printf("Please enter a floating point number and press ENTER.\n")
num, err := f... |
package services
import (
"context"
"github.com/satori/go.uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/tppgit/we_service/pkg/errors"
"testing"
"github.com/tppgit/we_service/core"
"github.com/tppgit/we_service/entity/user"
"github.com/tppgit/we_service/pkg/auth"
)
... |
package Problem0373
import "container/heap"
type pair struct {
i int
j int
sum int
}
type priorityQueue []*pair
func (pq priorityQueue) Len() int { return len(pq) }
func (pq priorityQueue) Less(i, j int) bool {
return pq[i].sum < pq[j].sum
}
func (pq priorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], ... |
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"sync"
)
type (
PoolCnt struct {
Bus chan []byte
sync.Mutex
m map[string]*PoolUnit
}
)
const (
BUS_LEN = 2000000
)
func NewPoolCnt() *PoolCnt {
bean := &PoolCnt{
Bus: make(chan []byte, BUS_LEN),
m: make(map[string]*PoolUnit),
}
go be... |
package main // import "github.com/kidoda/quikalarm"
import (
"github.com/spf13/pflag"
)
func main() {
var Usage = `Usage: quikalarm [options...] [arguments]
Simple alarm clock with few options.
Mandatory arguments to long options are mandatory for short options too.
Options:
-z, --snooze-time set snooze... |
package main
import (
"bytes"
"io"
"net/http"
"testing"
)
const webSite = "http://example.com"
func TestWget(t *testing.T) {
var buf, buf2 bytes.Buffer
if err := wget(webSite, &buf); err != nil {
t.Fatalf("%v", err)
}
resp, err := http.Get(webSite)
if err != nil {
t.Fatalf("%v", err)
}
defer resp.B... |
package stylei
import (
"database/sql"
"github.com/dropbox/godropbox/memcache"
"github.com/wgyuuu/storage"
)
func NewTesStorage(db *sql.DB, mc memcache.Client, prefereExpireTime int) storage.ComplexStorageProxy {
encoding := TesEncoding{}
msStorage := storage.NewComplexMysqlStorage(db, encoding)
mcStorage := s... |
package chrono
import "time"
type Zone string
type Format string
const (
Zone_UTC Zone = "UTC"
Zone_Bangkok Zone = "Asia/Bangkok"
)
const (
Format_ISO8601 Format = "2006-01-02T15:04:05.000-0700"
Format_TopValue Format = "2006-01-02 15:04:05"
)
var defaultZone Zone
var defaultLocation *time.Location
func ... |
package models
import (
"hotpler.com/v1/lib/common"
)
// Post data model
type Post struct {
Id string `gorm:"column:id;type:varchar(26);primary_key"`
CreateAt int64 `gorm:"column:create_at;type:bigint(20)"`
UpdateAt int64 `gorm:"column:update_at;type:bigint(20)"`
DeleteAt int64 `gorm:"column:delete_at;type... |
package main
import (
"context"
"database/sql"
"fmt"
irc "github.com/fluffle/goirc/client"
_ "github.com/lib/pq"
"github.com/saegewerk/GoTwitchRouter/pkg/config"
DB "github.com/saegewerk/GoTwitchRouter/pkg/db"
"github.com/saegewerk/GoTwitchRouter/pkg/twitchchat"
"github.com/saegewerk/GoTwitchRouter/pkg/twitch... |
package sort_util
import "github.com/Lxy417165709/LeetCode-Golang/新刷题/util/struct_util"
// QuickSort 快速排序。
func QuickSort(nums []int) {
// 1. 元素小于2的数组,直接返回。
if len(nums) < 2 {
return
}
// 2. 分区
index := Partition(nums)
// 3. 递归。
QuickSort(nums[:index])
QuickSort(nums[index+1:])
}
// Partition 分区。
func Pa... |
package pkg
var NameData [8]byte
var Name string |
package release
import (
"io/ioutil"
"os"
"github.com/ExploratoryEngineering/reto/pkg/toolbox"
)
const (
initialVersion = "0.0.0"
archiveDir = "release/archives"
releaseDir = "release/releases"
templateDir = "release/templates"
)
// InitTool initializes the directory structure for the tool. Errors... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.