text stringlengths 11 4.05M |
|---|
package sstats
import (
"math"
"testing"
)
func TestFisherUpdate(t *testing.T) {
sp, err := NewFisher(5)
if err != nil {
t.Fatal(err)
}
valx := []float64{1, 2, 3, 2, 1, 2, 3, 2, 1}
expected := []float64{0, 0.881, math.Inf(1), 0, -1.899, 0, 1.899, 0, -1.899}
for i, v := range valx {
sp.Update(v)
val := s... |
package main
import (
"context"
"time"
"github.com/gopherjs/gopherjs/js"
"github.com/goxjs/websocket"
"github.com/nayarsystems/gobbus"
)
func main() {
js.Global.Set("obbus", map[string]interface{}{
"connect": func(address string) *js.Object {
promise := js.Global.Get("Promise").New(func(res, rej func(inte... |
package config
import (
"github.com/nicksnyder/go-i18n/v2/i18n"
)
// 系统配置
type App struct {
Address string
Static string
Log string
Locale string
Language string
}
type Database struct {
Driver string
Address string
Database string
User string
Password string
}
type Configuration struct... |
package main
import (
"fmt"
"example.com/hello/composite/github"
)
func main() {
re, err := github.SearchIssues([]string{"vue", "vuex"})
if err != nil {
fmt.Println(err)
}
fmt.Println(re.TotalCount)
// fmt.Println(re.Items[:2])
// jsonMovie()
github.Text(re)
github.HTML(re)
}
func listTest(li []int) {
... |
package lc
import "sort"
// Time: O(n^2)
// Benchmark: 552ms 6.4mb | 9% 88%
func minMoves(nums []int) int {
if len(nums) <= 1 {
return 0
}
sort.Ints(nums)
var total int
pos := len(nums) - 1
for nums[0] != nums[pos] {
d := nums[pos] - nums[0]
total += d
for i := 0; i < pos; i++ {
nums[i] += d
}
... |
package metrics
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
func getAuthHeader(user, token string) string {
if user != "" && token != "" {
s := user + ":" + token
return "Basic " + base64.StdEncoding.EncodeToStrin... |
package catapult
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/Clever/ci-scripts/internal/environment"
"github.com/Clever/circle-ci-integrations/gen-go/client"
"github.com/Clever/circle-ci-integrations/gen-go/models"
"github.com/Clever/wag/logging/wagclientlogger"
)
// Artifact a... |
package main
const algoHighRiseThreshold1 = 0.20 // price rise ratio
/*
* High Rise Algorithm
* Description:
* Based on each KLine, if Close price > initialPrice, sell the gain part;
* otherwise, do nothing.
* The idea is to keep the remain 'value' at most as initialPrice.
*/
func algoHighRise(balanceBas... |
package main
import "fmt"
type Key struct {
v int
}
type Value struct {
v int
}
func main() {
var m map[string]string
m = make(map[string]string)
m["abc"] = "bbb"
fmt.Println(m["abc"])
m1 := make(map[int]string)
m1[53] = "ddd"
fmt.Println(m1[53])
fmt.Println(m1[55])
m2 := make(map[int]int)
m2[4] ... |
package main
import (
"review/zinx/net"
"review/zinx/ziface"
"fmt"
)
//创建路由控制器
type PingRouter struct {
net.BaseRouter
}
//处理业务之前的方法
func (r *PingRouter) PreHandle(request ziface.IRequest) {
fmt.Println("Call Router PreHandle ...")
_,err := request.GetConnection().GetTCPconnection().Write([]byte("before ping ... |
package main
import (
"fmt"
"math/rand"
"time"
)
// CODE OMIT
func foo1() {
for {
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
fmt.Println("foo1")
}
}
func main() {
// GO OMIT
go foo1() // HL
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
fmt.Println("main")
}
}
// END OMI... |
package main
import (
"github.com/google/uuid"
"log"
"os"
"strings"
)
func main() {
identifier := getUUID()
println(identifier)
println(strings.Replace(identifier, "-", "", 4))
}
func getUUID() string {
if len(os.Args) > 1 {
identifier, err := uuid.Parse(os.Args[1])
if err != nil {
log.Fatal("Format ... |
package DbService
import (
"fmt"
"ledger/DbUtil"
"time"
)
func WorkEntry_PreExe(workID string, workName string, ownerName string, adminName string, timeNow time.Time, txId string) []byte {
result := InsertWorkEntry_PreExe(workID, workName, ownerName, adminName, timeNow)
return result
}
func WorkEntry(workID str... |
package implementations
var KEY = "really_useful_object"
type SerializationObject struct {
String1, String2, String3, String4, String5 string
FieldX string
}
type Implementation interface {
Get() (object *SerializationObject, err error)
Set(object *SerializationObject) (err e... |
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package smb
import (
"context"
"io/ioutil"
"path/filepath"
"strings"
"time"
"golang.org/x/sys/unix"
"chromiumos/tast/common/testexec"
"chromiumos/tast/ctxutil"
"c... |
package main
import "fmt"
func main() {
fmt.Println("Hello, World!\n")
printMessage("Hi", "I am Ragul!")
fmt.Println("")
firstname := "Ragul"
lastname := "Ravindira"
printMessageTwo(&firstname, &lastname) // pointer parameters
fmt.Println("")
sum("The sum is: ", 1, 2, 3, 4, 5) // variatic parameters
fmt.Pr... |
package tsk
import (
"go4eat-api/pkg/tsk"
)
// NewList func
func NewList() *tsk.List {
return tsk.NewList([]*tsk.Task{
tsk.NewTask("server", "Run server", server),
tsk.NewTask("dbindexes", "Create database indexes", dbIndexes),
tsk.NewTask("places", "Create places", places),
})
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package common
import (
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)
func TestErrWithStatus(t *testing.T) {
t.Run("wrap in regular error and downcast", func(t *testing.T... |
package main
import (
"binary_tree/tree"
"fmt"
"log"
"os"
"strconv"
)
/*
Two nodes in a binary tree can be called cousins if they are on the same
level of the tree but have different parents. For example, in the
following diagram 4 and 6 are cousins.
1
/ \
2 3
/ \ \
4 5 6
Given a binary tree ... |
package main
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"log"
"net/http"
"os"
)
func randomString() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
log.Fatal(err)
}
uuid := fmt.Sprintf("%x%x%x%x%x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return uuid
}
func generateFileName() s... |
package main
import "fmt"
import "math"
const s string ="contant"
func main() {
fmt.Println(s)
const n = 5000000
const d = 3e20/n
fmt.Println(d)
fmt.Println(int(d))
fmt.Println(math.Sin(n))
} |
// Copyright 2009 Michael Stephens.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mongo
import (
"os";
"io";
"io/ioutil";
"net";
"fmt";
"rand";
"bytes";
"encoding/binary";
"container/vector";
)
var last_req int32
const (
_OP_REPLY = 1;
_O... |
package util
import (
"log"
"os"
"strings"
)
func Getenv(key string, def ...string) string {
res := strings.TrimSpace(os.Getenv(key))
if res == "" {
if len(def) == 1 {
return def[0]
}
log.Fatalln("missing", key)
}
return res
}
|
package odoo
import (
"fmt"
)
// AccountInvoiceRefund represents account.invoice.refund model.
type AccountInvoiceRefund struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,omptempty"`
Date ... |
package iterators
import (
"io"
)
// Iterator define a separate object that encapsulates accessing and traversing an aggregate object.
// Clients use an iterator to access and traverse an aggregate without knowing its representation (data structures).
// Interface design inspirited by https://golang.org/pkg/encoding... |
package datastore
import (
"errors"
"github.com/jelmerdereus/gowebtemplate/models"
"github.com/jinzhu/gorm"
)
// UserStore is an ORM layer that satisfies the UserRepo interface
type UserStore struct {
DBORM
}
// NewUserRepo is a constructor
func NewUserRepo(orm *DBORM) (UserRepo, error) {
if orm == nil {
ret... |
/*
Copyright 2021-2023 ICS-FORTH.
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... |
package messagequeue
import (
"encoding/json"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/streadway/amqp"
"log"
"math/rand"
"rabbitmqdemoProject/model"
"time"
)
func failError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
//func OpenCreater() {
//router := gin.Defau... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
var (
// Finds markdown links of the form [foo](bar "alt-text").
linkRE = regexp.MustCompile(`\[([^]]*)\]\(([^)]*)\)`)
// Splits the link target into link target and alt-text.
altTextRE = regexp.M... |
package main
import "gorm.io/gorm"
// 与另一个模型建立一对一的关联,但它和一对一关系有些许不同。 这种关联表明一个模型的每个实例都包含或拥有另一个模型的一个实例。
// 跟belongsto不同,模型之间并没有从属关系,同时关联不能为0
// User 有一张 CreditCard,UserID 是外键
type User struct {
gorm.Model
CreditCard CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
}
|
package codec
import (
"io"
"github.com/coinexchain/codon"
)
func ShowInfo() {
codon.ShowInfoForVar(nil, RangeProof{})
codon.ShowInfoForVar(nil, IAVLAbsenceOp{})
codon.ShowInfoForVar(nil, IAVLValueOp{})
}
var TypeEntryList = []codon.TypeEntry{
{Alias: "RangeProof", Value: RangeProof{}},
{Alias: "ProofInnerNo... |
package runtime
import (
"net/http"
xmpp "github.com/mattn/go-xmpp"
)
type HookHandler func(*xmpp.Client, []Hook) func(http.ResponseWriter, *http.Request)
var HookRegister map[string]HookHandler
func init() {
HookRegister = make(map[string]HookHandler)
}
|
// 本题为考试单行多行输入输出规范示例,无需提交,不计分。
package main
import (
"fmt"
)
func main() {
//test
a := 0
b := 0
c := 0
fmt.Scan(&a, &b, &c)
fmt.Printf("%d\n", a+b)
fmt.Printf("c=%d\n", c)
}
|
package tcpip
import "testing"
import "encoding/binary"
import "bytes"
func TestEthHdrDecode(t *testing.T) {
skb := alloc_skb(BUFLEN)
dmac := []byte{1, 1, 1, 1, 1, 1}
smac := []byte{2, 2, 2, 2, 2, 2}
copy(skb.data[0:6], dmac)
copy(skb.data[6:12], smac)
binary.BigEndian.PutUint16(skb.data[12:14], ETH_P_ARP)
hd... |
package p_00401_00500
// 415. Add Strings, https://leetcode.com/problems/add-strings/
import (
"strconv"
"strings"
)
func addStrings(num1 string, num2 string) string {
i := len(num1) - 1
j := len(num2) - 1
cnt := 0
var res []int
n := 0
for i >= 0 || j >= 0 {
sum := 0
sum += n
if i >= 0 {
sum += int... |
package cron
import (
"os"
"fmt"
"io"
"time"
)
var defaultFormat = func(Values ...interface{}) string {
var formattedArgs []interface{}
for _, arg := range Values {
if t, ok := arg.(time.Time); ok {
arg = t.Format("2006-01-02 15:04:05")
}
formattedArgs = append(formattedArgs, arg," ")
... |
package main
import(
"fmt"
"math"
)
func main(){
num := 600851475143 //infers 64bit int
sqrt := int(math.Sqrt(float64(num)))
found := false
var resulti int
var resultk int
for i := sqrt; i > 1; i--{
for k := 1; k < sqrt; k+=2{
fmt.Println(checkIfPrime(i), i,checkIfPrime(k), k)
if(i*k == num){
i... |
package backend
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math/big"
"strconv"
"github.com/cosmos/cosmos-sdk/client/flags"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/ethereum/go-ethereum/acco... |
package tencent
import (
"fmt"
"strconv"
"strings"
)
func Code1123() {
fmt.Println(isHappy(2))
}
/**
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
*/
/*... |
package main
import (
"fmt"
"sync"
parser "github.com/natsukagami/go-osu-parser"
)
const concurrentExtractors = 8
func extractor(input <-chan string, success chan<- BeatmapFile, fail chan<- error, wg *sync.WaitGroup) {
defer wg.Done()
for file := range input {
log("%s being parsed\n", file)
beatmap, err :=... |
package http
import (
"net/http"
"github.com/vikash/gofr/pkg/gofr/logging"
"github.com/vikash/gofr/pkg/gofr/http/middleware"
"github.com/rs/cors"
"github.com/gorilla/mux"
)
type Router struct {
mux.Router
}
func NewRouter() *Router {
muxRouter := mux.NewRouter().StrictSlash(false)
muxRouter.Use(
middlew... |
package main
import (
"fmt"
"os"
)
var _redis *RedisExecutor = nil
func main() {
//fmt.Println("Please select table.")
//repl()
WriteLn("redis cli")
args := os.Args[1:]
Debug("main", args)
e, opt, cmds := GetHostOpt(args)
if e != nil {
WriteLn(e)
os.Exit(1)
return
}
_redis = NewRedisExecutor(opt)
i... |
package main
type Video struct {
FileID string `json:"file_id"`
Width int `json:"width"`
Height int `json:"height"`
Duration int `json:"duration"`
Thumbnail *PhotoSize `json:"thumb"` // optional
MimeType string `json:"mime_type"` // optional
FileSize int `jso... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wpacli
import (
"bytes"
"context"
"io"
"os"
"reflect"
"strings"
"testing"
"chromiumos/tast/errors"
)
func TestSudoWPACLI(t *testing.T) {
testcases := []st... |
package veolia
import (
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
)
//func TestConsumption(t *testing.T) {
// veolia := NewVeolia()
// veolia.Username = "XXXXX"
// veolia.Password = "XXXXX"
// conso, err := veolia.getConsumption()
// if err != nil {
// t.Fatal(err)
// }
// for _, e := range conso {
// fmt.Pri... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package platform
import (
"context"
"net"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/bundles/cros/platform/screenlatency"
"chromiumos/tast/local/input"
... |
package dto
import "time"
type errorRespose struct {
Message string `json:"message"`
Description string `json:"description"`
Timestamp time.Time `json:"timestamp"`
}
func NewErrorResponse(msg string, desc string) errorRespose {
return errorRespose{Message: msg, Description: desc, Timestamp: time.Now(... |
package main
import (
"bytes"
"fmt"
"github.com/docopt/docopt.go"
"io"
"log"
"os"
)
func ByteToString(r io.ReadCloser) string {
buf := new(bytes.Buffer)
buf.ReadFrom(r)
return buf.String()
}
func main() {
arguments, err := docopt.Parse(usage, nil, true, "oclmagic v0.1", false)
if err != nil {
log.Fatal(... |
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package models
import "database/sql"
_ "github.com/mattn/go-sqlite3"
type User struct {
id int `json:"id"`
firstName string `json:"firstName"`
otherNames string `json:"otherNames"`
email string `json:"email"`
userName string `json:"userName"`
password string `json:"password"`
}
type UserCollectionDetails stru... |
package prime
import "math"
var pList = []int{2}
var pMap = map[int]bool{2: true}
var latest = 2
func IsPrime(param int) bool {
getPrimeUnder(param)
_, exist := pMap[param]
return exist
}
func getPrimeUnder(param int) {
if param <= 2 || param < latest {
return
}
for i := latest + 1; i <= param; i++ {
_i... |
/* ######################################################################
# Author: (__AUTHOR__)
# Created Time: __CREATE_DATETIME__
# File Name: server.go
# Description:
####################################################################### */
package main
import (
"__PROJECT_NAME__/controllers"
"__PROJECT_NAME__... |
package exactlyonce
import "github.com/payfazz/fazzkit/event/stan/message"
//Opt exactly once options
type Opt struct {
DbName string
Repository message.Repository
}
//NewOpt create exactly once options
func NewOpt(opt Opt) *Opt {
newOpt := &Opt{
DbName: opt.DbName,
Repository: opt.Repository,
}
ret... |
package models
type ChineseFoodSubGroup struct {
GroupID string `orm:"column(GroupID);size(10)"`
SubGroupID string `orm:"column(SubGroupID);size(10)"`
SubGroupName string `orm:"column(SubGroupName);size(255);null"`
}
|
package main
import "fmt"
type Books struct {
title string
author string
id int
}
func main() {
fmt.Print("hello world")
arr1 := [3]int{1,2,3}
fmt.Print(arr1)
slice := make([]int,0,10)
fmt.Print(slice)
//ptr, len, cap := slice
slice = append(slice, 1,2,3)
fmt.Println(slice,cap(slice),len(slice))
var ip ... |
package main
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
)
// var (
// text string
// )
func main() {
db, _ := sql.Open("mysql", "root:mice@/mice")
// defer db.Close()
fmt.Println(db)
// row, err := db.Exec("SHOW CREATE TABLE events")
// if err != nil {
// fmt.Println("err")
// if _,... |
package legacy
import (
"io"
"os"
"strconv"
)
type (
fileServer struct {
urlList FileTable
}
FileTable map[string]File
file struct {
contentType ContentType
path string
}
File interface {
ContentType() ContentType
File() (*os.File, error)
}
ContentType string
)
const (
ContentTypeHTM... |
package directorywatcher
import (
"os"
"path/filepath"
"time"
"github.com/adampresley/logging"
)
/*
DirectoryWatcher provides a set of functions to watch for changes on a directory. It allows
you to specificy a base and a function to be called when a change on an file occurs.
*/
type DirectoryWatcher struct {
B... |
package companyxchallenge
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
)
const (
firstnameConst = "FIRSTNAME"
lastnameConst = "LASTNAME"
// API endpoints. Hack: hardcode FIRSTNAME and LASTNAME into the Norris
// API so we can fetch a random name and get a random joke simultaneously.
na... |
/*
* Copyright (c) 2016, Shinya Yagyu
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of condition... |
// Copyright 2018 The gVisor 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 agree... |
package releases
var NoMgoSess = "nil pointer passed from session to Mongo"
var ErrReleaseNotFound = "Could not find a release for the given ID"
var ErrCategoryNotFound = "Could not find releases under specified category"
const ErrInsertNote = "Error inserting note: "
const ErrAddNoteToRelease = "Error adding note... |
package vehicle
import (
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/vehicle/volvo/connected"
)
// VolvoConnected is an api.Vehicle implementation for Volvo Connected Car vehicles
type VolvoConnected struct {
*embed
*connected.Provider
}
func init() {
registry... |
package main
import (
"fmt"
"time"
)
func main() {
// 创建一个判断是否终止的channel
quit := make(chan bool)
fmt.Println("now:", time.Now())
// 创建周期定时器
myTicker := time.NewTicker(time.Second) // 1s
i := 0
go func(){
for {
nowTime := <-myTicker.C
i++
fmt.Println("nowTime:", nowTime)
if i == 6 {
quit... |
package flipper
import (
"runtime"
"sync"
"testing"
)
func TestStackEquals(t *testing.T) {
s := &Stack{}
s.cakes = []bool{false, false, false, false, false, false}
test := []bool{false, false, false, false, false, false}
if !s.Equals(test) {
t.Errorf("equals failed valid %+v, %+v\n", s.cakes, test)
}
test... |
package Best_Time_to_Buy_and_Sell_Stock
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestBestProfit(t *testing.T) {
ast := assert.New(t)
case1 := []int{7, 1, 5, 3, 6, 4}
ast.Equal(maxProfit(case1), 5)
case2 := []int{7, 6, 4, 3, 1}
ast.Equal(maxProfit(case2), 0)
}
|
package main
import "golang.org/x/sys/windows"
func init() {
user32 := windows.NewLazySystemDLL("user32.dll")
defer func() {
_ = recover()
windows.FreeLibrary(windows.Handle(user32.Handle()))
}()
user32.NewProc("SetProcessDPIAware").Call()
}
|
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"strings"
"github.com/docker/go-plugins-helpers/ipam"
"github.com/docker/go-plugins-helpers/network"
"github.com/wrouesnel/go.log"
"github.com/wrouesnel/multihttp"
"github.com/wrouesnel/docker-vde-plugin/fsutil"
"gopkg.in/alecthomas/kingpin.v2"
"gi... |
package common
import "testing"
func Test_codeBlock(t *testing.T) {
type args struct {
header []string
in [][]string
}
tests := []struct {
name string
args args
want string
}{
{
name: "",
args: args{
header: []string{"A", "B", "C"},
in: [][]string{
{"AAAA", "BBBBB", "CCCCCCC"},
... |
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/CafeLucuma/go-play/plates/pkg/adding"
"github.com/CafeLucuma/go-play/plates/pkg/http/rest"
"github.com/CafeLucuma/go-play/plates/pkg/listing"
"github.com/CafeLucuma/go-play/plates/pkg/storage/postgres"
"github.com/joho/godo... |
package main
/*
Паттерн «Фасад», является структурным, т.е. отвечает за построение удобных в поддержке иерархий классов.
Т.е. «Фасад» - это простой интерфейс для работы со сложной подсистемой, содержащей множество классов,
а следовательно он определяет интерфейс более высокого уровня, который упрощает использование ос... |
package events
import (
"github.com/Phala-Network/go-substrate-rpc-client/v3/types"
)
type ChainBridgeEvents struct {
ChainBridge_FungibleTransfer []EventFungibleTransfer //nolint:stylecheck,golint
ChainBridge_NonFungibleTransfer []EventNonFungibleTransfer //nolint:stylecheck,golint
ChainBri... |
package errors
import (
"encoding/json"
"fmt"
)
type CodedError interface {
error
ErrorCode() Code
}
type Code uint32
const (
ErrorCodeGeneric Code = iota
ErrorCodeUnknownAddress
ErrorCodeInsufficientBalance
ErrorCodeInvalidJumpDest
ErrorCodeInsufficientGas
ErrorCodeMemoryOutOfBounds
ErrorCodeCodeOutOfBo... |
package main
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/4726/discussion-board/services/posts/models"
pb "github.com/4726/discussion-board/services/posts/read/pb"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/credenti... |
package model
import "time"
// DeletionPendingReport is a collection of configurable time cutoffs that are
// used to summarize installation deletion times. There is also an Overflow
// value that counts installations that fall outside all provided time cutoffs.
// Examples of DeletionPendingReport cutoffs:
// 1. Eve... |
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package simplecontroller
import (
"errors"
"fmt"
"time"
"github.com/mattermost/mattermost-load-test/loadtest/user"
)
type UserAction struct {
run func() user.UserStatus
waitAfter time.Duration... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wmp
import (
"context"
"fmt"
"strings"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/apps"
"chromiumos/tast/local/arc"
"... |
package usage
import (
"fmt"
"DA/3_stack/stack"
// "DA/6_tree/tree"
)
// HuffNode 节点
type HuffNode struct {
Weight int
Left int
Right int
Parent int
}
// HuffCode 编码
type HuffCode struct {
Weight int
code stack.OrderStack
}
// HtreeInit 树
func HtreeInit(weight []int) []HuffNode {
length := len(weight)
if... |
package main
import "fmt"
func init() {
}
func main() {
test_map_a()
}
//定义:map 是一种特殊的数据结构:一种元素对(pair)的无序集合,pair 的一个元素是 key,对应的另一个元
//素是 value,所以这个结构也称为关联数组或字典
//声明方式:var map1 map[keytype]valuetype var map1 map[string]int
//注意事项:1.未初始化的 map 的值是 nil,2.key 可以是任意可以用 == 或者 != 操作符比较的类型,比如 string、int、float。所以数组、切片和结构
/... |
package api
type Direction int
const (
Bottom Direction = iota
Top
North
South
West
East
)
type Position struct {
Vec3d
Vec2f
onGround bool
}
type Vec3d struct {
x, y, z float64
}
type Vec2f struct {
yaw, pitch float32
}
func (pos *Position) GetX() (x float64) {
if pos == nil {
return 0
}
x = pos.x
... |
package cache
import (
"github.com/kosotd/go-microservice-skeleton/cache"
"github.com/kosotd/go-microservice-skeleton/config"
"gotest.tools/assert"
"testing"
"time"
)
type testConfig struct {
config config.Config
}
func (c *testConfig) GetBaseConfig() *config.Config {
return &c.config
}
func init() {
conf :... |
package crawl
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
)
// A Page is a single page in a Site
type Page struct {
OrigURL url.URL // URL without any changes
URL url.URL // Final URL
Redirect *Page // Where this page redirec... |
//go:generate go-bindata -pkg tmpl -o tmpl_bindata.go -ignore '\.go' .
package tmpl
|
package herokuapi
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/carlmjohnson/errutil"
"github.com/spotlightpa/almanack/pkg/common"
)
func ConfigureFlagSet(fl *flag.FlagSet) *Configurator {
conf := Configurator{fl: fl}
fl.StringVar(&conf.apiKey, "heroku-api-key",... |
package utils
import "strconv"
func ToInt64(s string) (int64, error) {
n, err := strconv.ParseInt(s, 10, 64)
return n, err
}
func MustToInt64(s string) int64 {
n, err := ToInt64(s)
if err != nil {
panic(err)
}
return n
}
|
package main
import (
"github.com/life-assistant-go/utils"
)
func main() {
type YY struct {
Path string
}
type TestGorm struct {
Title string `gorm:"not null;"`
Tag string
YY
}
var test = TestGorm{
Title: "",
Tag: "333",
}
utils.ValidateStruct(test)
utils.DB.Create(&test)
// app.DBTable()
/... |
package server
import (
"github.com/labstack/echo"
"net/http"
)
func handleReportState(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{
"message": "ok",
})
}
func handleFulfillState(c echo.Context) error {
return c.JSON(http.StatusOK, State{
Properties: []Property{
{
Action: ... |
package arrays
import (
"fmt"
)
func main() {
a := make([][]int, 3)
count := 1
for i := 0; i < 3; i++ {
a[i] = make([]int,3)
for j := 0; j < 3; j++ {
a[i][j] = count
count++
}
}
fmt.Println(rotateImage(a))
}
func rotateImage(a [][]int) [][]int {
new := make([][]int, len(a))
for i := 0; i < len(... |
package main
import "fmt"
import "sync"
func main() {
wg := &sync.WaitGroup{}
wg.Add(2)
ch1 := make(chan int, 0)
//ch2 := make(chan int,0)
arr1 := [5]int{0, 2, 4, 6, 8}
arr2 := [5]int{1, 3, 5, 7, 9}
go func() {
for i, v := range arr1 {
ch1 <- i
fmt.Println(v)
<-ch1
}
wg.Done()
}()
go func() {... |
/*
Copyright 2022 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
// Copyright © SAS Institute 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... |
package main
import (
"fmt"
"sort"
)
// type a os.File
// type b io.Writer
// type c bytes.Buffer
// type d time.Duration
// var w io.Writer
// var rwc io.ReadWriteCloser
// var x interface{} = time.Now()
// func main() {
// w = os.Stdout
// w = new(bytes.Buffer)
// rwc = os.Stdout
// // rwc = new(bytes.... |
package handler
import (
"net/http"
"github.com/go-chi/render"
"github.com/pagient/pagient-server/pkg/model"
"github.com/pagient/pagient-server/pkg/presenter/renderer"
"github.com/pagient/pagient-server/pkg/presenter/router/middleware/context"
"github.com/pagient/pagient-server/pkg/service"
)
// GetPatients li... |
package main
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func largestValues(root *TreeNode) []int {
var ret = []int{}
var dfs func(r *TreeNode, idx int)
dfs = func(r *TreeNode, idx int) {
if r == nil {
return
}
if ... |
// Copyright (c) 2020 Tailscale Inc & 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 tsaddr handles Tailscale-specific IPs and ranges.
package tsaddr
import (
"sync"
"inet.af/netaddr"
)
// ChromeOSVMRange returns the ... |
package main
import (
"github.com/oceanho/gw/contrib/apps/stor"
)
var AppPlugin stor.App
func init() {
AppPlugin = stor.New()
}
|
// 139. Sort 格式化 分類 排序 直接更改記憶體位置的值所以不用return
// https://golang.org/pkg/sort/
package main
import (
"fmt"
"sort"
)
func main() {
s := []int{5, 2, 6, 3, 1, 4} // unsorted
x := []string{"and", "q", "M", "ming", "Dr.", "zo", "xxx", "ga", "A"}
fmt.Println(s)
sort.Ints(s)
fmt.Println(s)
fmt.Println(x)
sort.Strin... |
package main
import "sort"
func minMeetingRooms(intervals [][]int) int {
if len(intervals) < 1 {
return 0
}
//var array svalue = intervals
//sort.Sort(array)
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][1] < intervals[j][1]
})
max := 1
count := 1
for i, v := range intervals {
count =... |
// Copyright 2019 - 2022 The Samply Community
//
// 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 ... |
package main
import "k8s-client/example"
func main(){
//var kubeconfig *string
//if home := homedir.HomeDir(); home != "" {
// kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
//} else {
// kubeconfig = flag.String("kubeconfig", "",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.