text stringlengths 11 4.05M |
|---|
package main
func main() {
//keyboardExample()
//miceExample()
//touchPadExample()
//touchScreenExample()
}
|
package main
// atomic counters - accessed by multiple go routines
import "fmt"
import "time"
import "sync/atomic"
func main() {
var ops uint64 // unsigned int to represent always positive counter
for i := 0; i < 50; i++ { // start 50 go routines
go func() {
for {
atomic.AddUint64(&ops, 1) // add via me... |
package main
import (
"bytes"
"testing"
)
func TestEncodeUTF32BE(t *testing.T) {
res := EncodeUTF32BE([]uint32{
0x0068, // Latin Small Letter H
0x0065, // Latin Small Letter E
0x0079, // Latin Small Letter Y
0x1F64C, // Person Raising Both Hands In Celebration Emoji
})
expected := []byte{
0x00, 0x00... |
package controllers
import (
"encoding/json"
"ss-backend/models"
"github.com/astaxie/beego"
)
type (
// PemesananController ...
PemesananController struct {
beego.Controller
}
)
// Get all data product
func (c *PemesananController) Get() {
var resp RespData
var order models.Pemesanan
var reqDt = models.R... |
package utils
import (
"lili_style_test/sheets"
)
func SearchUserDataByMail(mail string) []string {
formData := sheets.GetAll()
for _, d := range formData {
if d[1] == mail {
user := convertInterfaceToString(d)
return user
}
}
return nil
}
func SearchUserDataBySlash(mail string) []string {
formData :... |
// Copyright (c) 2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"io/ioutil"
"log"
"os"
"os/exec"
"time"
rpc "github.com/conformal/btcrpcclient"
"github.com/conformal/btcutil"
"github.com/conformal/btcwire"
)... |
package tritondb
import (
"database/sql"
"errors"
"fmt"
"github.com/tada3/triton/weather/model"
)
const (
selectPreferredCitySQL = "SELECT id from preferred_city WHERE name = ? ORDER BY priority DESC"
selectCityListSQL = "SELECT id from city_list WHERE name = ?"
removeShiSQL ... |
package bot
import(
"os"
"sync"
api "gopkg.in/telegram-bot-api.v4"
"github.com/deepdeeppink/tgbot/errs"
"github.com/deepdeeppink/tgbot/users"
"github.com/deepdeeppink/tgbot/cfg"
)
const (
BC_CONFIRM = "Отправить"
BC_DECLINE = "Отмена"
)
var (
E = errs.E()
userlist = users.Get()
config = cfg.GetConfig()
... |
package main
import (
"net/http"
"log"
"github.com/99designs/gqlgen/handler"
"github.com/go-chi/chi"
grap "github.com/siulfe/gql"
DDBB "github.com/siulfe/gql/Database"
)
const defaultPort = "8080"
func main() {
resp,err := DDBB.LeerArchivo()
log.Println("Respuesta: ",resp)
if err != nil{
panic(err)
}
... |
package health
import (
"context"
"time"
"github.com/jmoiron/sqlx"
"github.com/movieManagement/gen/models"
"github.com/movieManagement/gen/restapi/operations/health"
)
// Service handles async log of audit event
type Service interface {
HealthCheck(ctx context.Context, in *health.GetHealthParams) (*models.Heal... |
package fare
import (
"context"
"github.com/stamm/wheely/apis/distance/types"
faretypes "github.com/stamm/wheely/apis/fare/types"
)
type IFareService interface {
Calculate(ctx context.Context, start, end types.Point) (faretypes.Result, error)
}
|
package main
import "fmt"
import "math/rand"
import "time"
import "sync/atomic"
func main() {
thread_count := 4
var in int64 = 0
var total int64 = 0
lim := 2147483647
seed := rand.NewSource(time.Now().UnixNano())
random := rand.New(seed)
ch := make(chan int)
for i := 0; i < thread_count; i++{
go func(){
... |
package util
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func GenerateID() string {
hi := rand.Uint64()
lo := rand.Uint32()
return fmt.Sprintf("%x%x", hi, lo)
}
|
package firewall
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test_iptablesCommand(t *testing.T) {
successCmd := func() *MockExecer {
e := &MockExecer{}
e.On("Exec").Return([]byte("output"), nil)
return e
}
Convey("Given an iptablesCommand", t, func() {
execFactory := &MockEx... |
// Copyright 2017 Vector Creations Ltd
//
// 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 agre... |
package factoryreset
import (
"os"
"path/filepath"
"github.com/rancher-sandbox/rancher-desktop/src/go/rdctl/pkg/autostart"
"github.com/rancher-sandbox/rancher-desktop/src/go/rdctl/pkg/paths"
"github.com/sirupsen/logrus"
)
func DeleteData(paths paths.Paths, removeKubernetesCache bool) error {
if err := autostar... |
package Problem0115
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Problem0115(t *testing.T) {
ast := assert.New(t)
// tcs is testcase slice
tcs := []struct {
s string
t string
ans int
}{
{
"aaaaaa",
"",
1,
},
{
"aaaaaa",
"aa",
15,
},
{
"... |
package main
import (
"finrgo/exhanges"
"finrgo/exhanges/bittrex"
"finrgo/exhanges/polo"
"fmt"
"github.com/davecgh/go-spew/spew"
)
const (
BittrexExchange string = "bittrex"
PoloniexExchange string = "poloniex"
)
func main() {
exchanges := exhanges.InitExhanges()
exchanges.AddExhange(BittrexExchange, &bitt... |
package philifence
type PolyRing struct {
Coordinates []Coordinate
Box Box
}
func MakePolyRing(length int) *PolyRing {
return &PolyRing{
Coordinates: make([]Coordinate, length),
}
}
func NewPolyRing(coords ...Coordinate) *PolyRing {
return &PolyRing{
Coordinates: coords,
}
}
func (pr *PolyRing) Len() in... |
package yadisk
import (
"net/http"
"net/url"
"strconv"
"strings"
)
// Get meta-information about a public file or directory.
func (yad *yandexDisk) GetPublicResource(publicKey string, fields []string, limit int, offset int, path string, previewCrop bool, previewSize string, sort string) (r *PublicResource, e erro... |
package installer
import (
"airdb/helpers"
"fmt"
"os"
)
func serverInstaller() {
fmt.Println("Configuring airdb server using supervisor.d ....")
fmt.Print("Enter your desired server port where airdb is going to run: ")
var port string
_, err := fmt.Scanf("%s\n", &port)
if err != nil {
fmt.Println("Error " +... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"github.com/russross/blackfriday"
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] input output\n", path.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, "https://foosoft.net/projects/md2vim/\n\n")
fmt.Fprintf(os.Stderr, "Parameters:\n")
... |
// 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 service
import (
"github.com/ankurs/Feed/Feed/service/store"
)
type Config struct {
Store store.Config
Worker WorkerConfig
}
type WorkerConfig struct {
Host string
Queue string
Username string
Password string
}
|
// 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 i... |
package teams
import (
"database/sql"
"errors"
)
type Team struct {
Name string `json:"teamname"`
Count_clicks int `json:"clicks"`
Number_of_members int `json:"member_count"`
}
const tableCreationQuery = `CREATE TABLE IF NOT EXSIST team(
teamname text PRIMARY KEY,
count_game_u... |
package dbops
import (
"XianZhi/clog"
"fmt"
"testing"
)
func TestMain(m *testing.M) {
_ = clog.InitLogger("console",clog.Config{Log_level:"debug"})
//clearTables()
m.Run()
//clearTables ()
}
func clearTables() {
//清除数据库数据
//_,_ = dbConn.Exec("truncate table")
}
func TestRun(t *testing.T) {
t.Run("Selec... |
package bucket
import (
"context"
"io/ioutil"
"os"
"strings"
"testing"
"time"
"github.com/fishy/fsdb"
)
func TestMock(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode")
}
ctx := context.Background()
delay := time.Millisecond * 50
total := delay * 2
shorter := time.Millisecond... |
package syncInterface
import (
syncComm "github.com/HNB-ECO/HNB-Blockchain/HNB/sync/common"
)
type SyncServiceInf interface {
SyncToTarget(chainID string, beginCursor uint64, endCursor uint64, peerId uint64, isBlocked bool, version uint32, ntyCunc syncComm.NotifyFunc) error
GetSyncState(chainID string) (uint8, er... |
package machine
import (
"fmt"
"math/rand"
"os"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
// TestRead reads several config files and verifies the output.
func TestRead(t *testing.T) {
const correctCount = 3
const incorrectCount = 7
for i := 1; i <= correctCount; i++ {
_, err := Read(fmt.Sprintf("... |
package reader
import (
"encoding/json"
"io"
"io/ioutil"
)
type jsonReader struct {
input io.Reader
}
func (j jsonReader) Unmarshal(object interface{}) error {
return json.NewDecoder(j.input).Decode(object)
}
func (j jsonReader) Valid() bool {
var test map[string]interface{}
return j.Unmarshal(&test) == nil
... |
/*
Tencent is pleased to support the open source community by making Basic Service Configuration Platform available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain... |
package spider
type Novel struct {
NovelId int `json:"novel_id"`
NovelHash string `json:"novel_hash"`
DownloadUrl string `json:"download_url"`
VoteUrl string `json:"vote_url"`
NovelType string `json:"novel_type"`
Size int `json:"size"`
Title string `json:"title"`
Detail string `js... |
package pagination
import (
"bytes"
"testing"
"github.com/PuerkitoBio/goquery"
)
func assertHasHTMLElements(t *testing.T, html *goquery.Document, selector string, num int) {
got := html.Find(selector)
if got.Length() != num {
t.Errorf("Expected to find %d html elements (%s) but found %d", num, selector, got.L... |
package cache
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"sync"
"time"
)
// Internal structure to track old files, sort them by age and delete "sets"
// of them.
type fsCacheEntry struct {
ns string
uuidAndHash []byte
size int64
time time.Time
}
ty... |
package server
import (
"bufio"
"context"
"encoding/json"
"fmt"
"go-bca"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
"github.com/julienschmidt/httprouter"
"golang.org/x/sync/singleflight"
)
va... |
package bmdb
import (
"errors"
"github.com/missionMeteora/bmdb/mdb"
)
const registryMapCap = 128
const (
// MaxNameLength is the maximum length of a bucket name, in bytes.
MaxNameLength = 64
// MaxKeySize is the maximum length of a key, in bytes.
MaxKeySize = 32768
// MaxValueSize is the maximum length of a ... |
package model
type Document struct {
Id string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
}
type Documents []Document
func (d Documents) Len() int {
return len(d)
}
func (d Documents) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
func (d Documents) Less(i, j int) bool {
if d[i].Id < d[j].... |
package main
import "fmt"
func main() {
fmt.Println(len("hello this is i love the len function"))
fmt.Println("Something with a \n new line"[10]) // returns the byte representation of the value
fmt.Println("hello"[0]) // returns the byte representation of the value
fmt.Println("hhllo"[1]) ... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package kubernetes
import (
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// TODO These interfaces do... |
package main
import (
"golang.org/x/net/html"
"io"
"net/http"
"fmt"
"strings"
)
// Represents a DOM-Query
// Also represents recursively the whole query-chain
type Query struct {
tokenizer *html.Tokenizer //Contains the tokenized HTML DOM
hasPrevQuery bool
hasNextQuery bool // Has next query?
prevQuery *Que... |
// Implementation of default update service.
//
// @author TSS
package service
import (
"os"
"path/filepath"
"github.com/mashmb/1pass/1pass-core/core/domain"
"github.com/mashmb/1pass/1pass-core/port/out"
)
type dfltUpdateService struct {
updater out.Updater
}
func NewDfltUpdateService(updater out.Updater) *df... |
package beacon_test
import (
beacon "."
"github.com/pkg/errors"
"sync"
"testing"
"time"
)
// MockRuntime emulates a real Runtime implementation.
type MockRuntime struct {
Events chan *beacon.Event
}
// EmitEvents returns the MockRuntime.Events channel.
func (r *MockRuntime) EmitEvents() (<-chan *beacon.Event, ... |
package service
import (
"heroku-backend-a-cocreate/dto"
"heroku-backend-a-cocreate/helper/bc"
"heroku-backend-a-cocreate/model"
"heroku-backend-a-cocreate/repository"
)
type AuthService interface {
VerifyCredential(email, password string) interface{}
CreateUser(user dto.RegisterDTO) model.User
IsDuplicateEmai... |
package ginplugin
import (
"crypto/rand"
"encoding/base32"
"io"
"strings"
"github.com/sirupsen/logrus"
)
var sessionUtilsLogger = logrus.New()
func NewSessionId() string {
k := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, k); err != nil {
sessionUtilsLogger.Errorf("generate session id failed:%s",... |
package main
import (
"fmt"
"encoding/hex"
"github.com/lt/go-cryptopals/cryptopals"
)
func main() {
expected, _ := hex.DecodeString("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f")
input := []byte("Burning 'em,... |
package rpc
import (
"context"
"fmt"
"github.com/benka-me/users/go-pkg/jwt"
"github.com/benka-me/users/go-pkg/users"
)
func (app *App) Auth(ctx context.Context, req *users.Token) (*users.IsAuth, error) {
err := jwt.CheckJwt(req.Val)
fmt.Println("auth err:", err, req.Val)
return &users.IsAuth{Val: err == nil},... |
package honeycombio
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
func TestQueryAnnotations(t *testing.T) {
ctx := context.Background()
c := newTestClient(t)
dataset := testDataset(t)
var queryAnnotation *QueryAnnotation
var err error
query, err := c.Queries.Create(ctx, dataset, &Qu... |
package main
import (
"math"
"strconv"
)
var columnID int = 1
var floorRequestButtonID int = 1
var floor int = 1
type Battery struct {
ID int
status string
columnsList []Column
floorRequestButtonsList []FloorRequestButton
}
func NewBattery(_id, _amountOfColumn... |
package batcave
//import (
// "encoding/gob"
//)
const file = "/tmp/tasks.gob"
// TaskDatabase is an alias for a map, where the key is userID, and value is list of tasks
type TaskDatabase map[string][]string
// NewTaskDatabase creates an new object for this type
func NewTaskDatabase() TaskDatabase {... |
package main
/*
NOTE:
- $ go test //to run tests
UNIT TEST
- $ go test -cover //to check test coverage
- $ go tool cover -html=coverage.out //generate coverage.out file which is used to generate a HTML page which shows exactly what lines have been covered
BENCHMARK TEST
- $ go test -bench=. //runs all benchmarks withi... |
package main
import (
"encoding/json"
"fmt"
"net"
"strconv"
"time"
)
const (
STEP_WAIT_MS = 75
)
type Room struct {
Connections []net.Conn
Name string
}
type Game struct {
Players []NetworkPlayer
Step int
}
type NetworkPlayer struct {
Connection net.Conn
Alive bool
Moves []Move
... |
package main
import (
"log"
"time"
"net/url"
cmc "github.com/coincircle/go-coinmarketcap"
"fmt"
"telegram-bot-api"
"strings"
)
func checkTransactions() {
t := time.Now().UTC().Format(time.RFC3339)
for {
time.Sleep(1 * time.Minute)
log.Print("Started checking")
rows, _ := db.Table("wallets").Rows()
fo... |
// Package sqlRequests
/*
Пакет для запросов к БД
В запросах участвуют структуры (Item, User, UsersItemsRows), через поля которых передаётся информация
*/
package sqlRequests
type Item struct {
Id *int `db:"item_id"`
Name *string `db:"item_name"`
UserId *int `db:"item_user_id"`
CreateAt *string... |
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/linkedlocked/webapp/models"
"strconv"
)
/*
Router Card Code
*/
func routeGetCardsByUser(c *gin.Context) {
objects := models.GetCardsByUser(int(GetPageVariables(c).User.ID))
c.JSON(200, objects)
}
func routeDeleteCard(c *gin.Context) {
id, err... |
package skylarkutils
import (
"reflect"
"testing"
"github.com/google/skylark"
"github.com/kr/pretty"
)
// makes tests more compact
type str = skylark.String
type tup = skylark.Tuple
func TestListToGo(t *testing.T) {
tests := []struct {
name string
l *skylark.List
i interface{}
}{
{
name: "st... |
package main
import (
"bitbucket.org/kardianos/table"
_ "code.google.com/p/odbc"
"database/sql"
"fmt"
"log"
"os"
"time"
)
func main() {
connStr := "driver=sql server;server=(local);database=tempdb;trusted_connection=yes"
if len(os.Args) > 1 && len(os.Args[1]) > 1 {
connStr = os.Args[1]
}
//log.Printf("Co... |
package pool
import (
"context"
"github.com/mee6aas/kyle/internal/pkg/runtime"
)
var (
mngCtx context.Context
mngCancel context.CancelFunc
rConf runtime.Config
onFetched = make(chan struct{}, 1)
)
|
// +build !windows
package version_test
import (
"io/ioutil"
"os"
"github.com/cloudfoundry-incubator/ltc/version"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("FileSwapper", func() {
Describe("#SwapTempFile", func() {
var (
srcPath string
destPath string
ap... |
package topic
type useCase struct {
repository Repository
}
type Repository interface {
Save(command *addTopicCommand) error
List(command *listTopicQuery) ([]topicModel, error)
}
func (u *useCase) add(command *addTopicCommand) error {
return u.repository.Save(command)
}
func (u *useCase) list(command *listTopic... |
// See LICENSE.txt for licensing information.
package simpleini
import (
"bytes"
"fmt"
"io"
"os"
"strings"
"testing"
)
func TestParsingCorrectInputs(t *testing.T) {
var input io.Reader
inputs := [...]string{
`[main]
string = this is a test
integer = 123
boolean = yes
[auxillary]
whatever = something
`,
... |
package main
import (
"fmt"
"os"
)
func main(){
i:=0
for{
i++
fmt.Println("Helllooooooo")
if i==10{
break
}
}
for i:=0;i<10;i++{
fmt.Println("worlddddddddddddddddd")
}
for i:=true;i;i=false{
fmt.Println(i)
}
arguments := os.Args
if len(arguments) ==1{
fmt.Println("no argument provided... |
package main
import (
"fmt"
"net"
"strconv"
"time"
msgpack "gopkg.in/vmihailenco/msgpack.v2"
)
type UDPRequest struct {
One string
Two int
Three string
}
func main() {
fmt.Println("Starting client")
serverAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8084")
if err != nil {
fmt.Println(err)
r... |
// 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 controllers
import (
"context"
"net/http"
"time"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/AskJag07/virtuoso-server/models"
)
func Students(client *mongo.Client) gin.HandlerFunc {
return... |
package main
import "math"
func main() {
}
func integerBreak(n int) int {
if n <= 3 {
return n - 1
}
quotient := n / 3
remainder := n % 3
if remainder == 0 {
return int(math.Pow(3, float64(quotient)))
} else if remainder == 1 {
return int(math.Pow(3, float64(quotient-1))) * 4
}
return int(math.Pow(3, ... |
package vo
type TestResult struct {
//service.MatchLast `xorm:"extends"`
//Id string
//Name string
//CompName string
//entity2.EuroLast `xorm:"extends"`
}
|
package main // 包
import (
"log"
"net/smtp"
"github.com/jordan-wright/email"
)
func main() { // 入口函数
e := email.NewEmail() // := 定义且赋值
e.From = "1137807913@qq.com"
// [] Array 多个用户发邮件 { }集合
e.To = []string{"525876818@qq.com", "1733407461@qq.com", "2426298429@qq.com", "498165738@qq.com"}
e.Subject = "你在家还... |
package redis
import (
"encoding/json"
"errors"
"time"
"github.com/gomodule/redigo/redis"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
)
// DelayData struct
type DelayData struct {
UUID string `json:"uuid"` // UUID for delay value
Time int64 `json:"time"` // the unix timestamp to trigge... |
package query
import (
"context"
"github.com/angryronald/guestlist/internal/guest/domain/service/guest"
"github.com/angryronald/guestlist/internal/guest/public"
)
// CountEmptySeatsQuery encapsulate process for count empty seats in Query
type CountEmptySeatsQuery struct {
service guest.ServiceInterface
}
// New... |
package webhooks
import (
"context"
"net/http"
ctrl "sigs.k8s.io/controller-runtime"
"time"
)
const (
webhookDefaultTimeout = 10 * time.Second
)
type contextKey struct{}
func NewContextFromRequest(ctx context.Context, req *http.Request) context.Context {
query := req.URL.Query()
timeout := query.Get("timeout... |
package hash
import (
"crypto/rand"
"testing"
"github.com/stretchr/testify/require"
)
func TestHash(t *testing.T) {
data1 := []byte("The Cypherpunks are actively engaged in making the networks safer for privacy.")
hash1, err := Hash("ciphertext", data1)
require.NoError(t, err)
hash2, err := Hash("plaintext", ... |
package models
import (
"github.com/jinzhu/gorm"
)
//研发推广
type Application struct {
BaseModel
Name string `json:"name" form:"name"` //名称
Code string `json:"code" form:"code"` //编码
CategoryId int `json:"category_id" form:"category_id"` //分类
Category *Category... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
package main
//Printing a number in decimal, binary and hexadecimal formats
import "fmt"
func main() {
num := 1618
fmt.Printf("dec = %v\nbin = %b\nhex = %#x", num, num, num)
}
|
package main
import (
"encoding/csv"
"io"
"io/ioutil"
"strings"
"os"
)
// WriteOutput writes a csv file (specified in filename) from a slice of strings (specified in words)
func WriteOutput(words []string, filename string) {
// create file
f, err := os.Create(filename)
Check(err)
//... |
package main
import (
"fmt"
"sort"
)
// 47. 全排列 II
// 给定一个可包含重复数字的序列,返回所有不重复的全排列。
// https://leetcode-cn.com/problems/permutations-ii/
func main() {
nums := []int{1, 1, 2}
fmt.Println(permuteUnique1(nums))
fmt.Println(permuteUnique2(nums))
}
// 要点:在cur的同一个位置,不能使用重复数字
// 法一:时间最优
// 法二:空间最优
// 法一:通过排序 和 i > 0 &... |
// Package sample models an audio sample
package sample
import (
"testing"
)
func TestValueFromByteU8(t *testing.T) {
//TODO: Test
}
func TestValueFromByteS8(t *testing.T) {
//TODO: Test
}
func TestValueFromBytesU16LSB(t *testing.T) {
//TODO: Test
}
func TestValueFromBytesU16MSB(t *testing.T) {
//TODO: Test
}... |
package schema
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/Juniper/contrail/pkg/common"
"github.com/flosch/pongo2"
)
//TemplateConfig is configuration option for templates.
type TemplateConfig struct {
TemplateType string `yaml:"type"`
TemplatePath string `yaml:"template_path"`
OutputPat... |
package main
import (
"flag"
"fmt"
"log"
"net"
"runtime"
"strconv"
"sync"
"time"
)
func genGameId() chan int {
ch := make(chan int)
go func() {
for i := 0; ; i++ {
ch <- (i*37+39)%(*games) + 1
}
}()
return ch
}
func genO1() chan string {
ch := make(chan string)
go func() {
for {
select {
... |
package reader
import (
"fmt"
"os"
"sync"
)
type resultWriter struct {
fileName string
resChan chan responseResult
wg *sync.WaitGroup
}
func newResultWriter(fileName string, resChan chan responseResult, wg *sync.WaitGroup) *resultWriter {
return &resultWriter{
fileName: fileName,
resChan: resChan,... |
package client
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"path/filepath"
"github.com/go-gonzo/npm/commonjs/package"
)
const pkgNotFound = "Package (%s@%s) Not Found."
const (
NPM = "http://registry.npmjs.org/"
)
func Get(name, version string) (*pkg.Package, error) {
npm, err := url.Parse(NPM)
... |
package issuer
import (
"context"
"strings"
"github.com/kumahq/kuma/pkg/core/resources/apis/system"
"github.com/kumahq/kuma/pkg/core/resources/manager"
core_model "github.com/kumahq/kuma/pkg/core/resources/model"
core_store "github.com/kumahq/kuma/pkg/core/resources/store"
)
var RevocationsSecretKey = core_mod... |
package repository
import (
"github.com/asdine/storm"
"github.com/cswank/quimby/internal/schema"
)
// Gadget does database-y things.
type Gadget struct {
db *storm.DB
}
func newGadget(db *storm.DB) *Gadget {
return &Gadget{
db: db,
}
}
func (g Gadget) GetAll() ([]schema.Gadget, error) {
var out []schema.Gad... |
package day05
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
func MarshalUnmashalArr() {
var arr [3]string
marshalArr(arr)
unmarshalArr(arr)
}
func marshalArr(arr [3]string) { //编码JSON
fmt.Println("------编码JSON------")
arr = [3]string{"足球", "篮球", "乒乓球"}
if bytSli, err := json.Marshal(arr); err != nil {
l... |
package model
type Model struct {
ID uint32 `gorm:"primary_key" json:"id`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
CreatedOn uint32 `json:"created_on"`
ModifiedOn uint32 `json:"modified_on"`
DeletededOn uint32 `json:"deleted_on"`
IsDel uint `json:"is_del... |
package log
import (
"github.com/astaxie/beego/logs"
)
var (
log *logs.BeeLogger
)
func init() {
log = logs.NewLogger()
log.SetLogFuncCallDepth(3)
log.SetLogger(logs.AdapterConsole)
log.EnableFuncCallDepth(true)
log.Debug("this is a debug message")
}
func Info(format string, v ...interface{}) {
log.Info(for... |
package main
import (
"EsAlertLog/Service"
"EsAlertLog/utils"
"flag"
"fmt"
)
func Processor() {
logger:=utils.CreateLogger()
espath := flag.String("c", "", "Elasticsearch连接配置文件路径")
rulepath := flag.String("f", "", "告警规则配置文件路径")
mailpath := flag.String("m", "", "发件箱信息")
flag.Parse()
Ei, err := utils.NewEsInf... |
package string
import "strings"
// strings.Index的UTF-8版本
// 即 Utf8Index("Go语言中文网", "中文") 返回 4,而不是strings.Index的 8
func Utf8Index(str, substr string) int {
asciiPos := strings.Index(str, substr)
if asciiPos == -1 || asciiPos == 0 {
return asciiPos
}
pos := 0
totalSize := 0
reader := strings.NewReader(str)
for... |
package heap
import "fmt"
type minHeap struct {
Capacity int
Array []int
}
func NewEmptyMinHeap() Heap {
return &minHeap{
Capacity: 0,
Array: make([]int, 0),
}
}
func (h *minHeap) AddElement(e int) {
h.Array = append(h.Array, e)
h.Capacity++
j := h.Capacity - 1
for j > 0 {
if h.Array[j] < h.Arra... |
package ansilog
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"os"
"time"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/oblq/ansilog/internal/hooks/pghook"
"github.com/oblq/ansilog/internal/hooks/stack_trace"
"github.com/oblq/swap"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type T... |
package pool
import (
"container/heap"
"fmt"
"time"
"github.com/zmb3/spotify"
)
type Pool struct {
PlaylistID spotify.ID `json:"playlistid"`
PlaylistName string `'json:"playlist_name`
UserID string `json:"userid"`
// TimeStarted
SongHeap []*Song `json:"songheap"`
UserToVoteMap map[string][]string
}... |
package main
import (
"log"
"os"
"bytes"
"compress/gzip"
"io"
"flag"
"strings"
"github.com/hoisie/mustache"
"io/ioutil"
"regexp"
"fmt"
"github.com/murz/eg/proxy"
"github.com/murz/eg/templates"
)
func main() {
var path string;
flag.StringVar(&path, "path", "/", "")
args := os.Args[1:len(os.Args)] // th... |
package live
import (
"github.com/gorilla/websocket"
)
func NewWebSocketClient(addr, id, host string) (*Client, error) {
wsConn, _, err := websocket.DefaultDialer.Dial(addr, nil)
if err != nil {
return nil, err
}
transport := NewWebSocketTransport(wsConn)
cli, err := NewClientWithTransport(transport, id, hos... |
package actions
import (
"github.com/mezis/klask/config"
"github.com/mezis/klask/index"
"net/http"
)
func OnIndicesCreate(res http.ResponseWriter, req *http.Request) {
defer failMessage(res)
resource, err := index.New("unnamed", config.Pool())
abortOn(err)
requestJson(req, &resource)
exists, err := resourc... |
package gcp
import "testing"
func TestGetNameFromURL(t *testing.T) {
var testCases = []struct {
item, url, expected string
}{
{
item: "zones",
url: "https://www.googleapis.com/compute/v1/projects/ci-op-lk2ifbjc/zones/us-central1-a",
expected: "us-central1-a",
},
{
item: "networks",
... |
//
// Copyright (c) 2017, Stardog Union. <http://stardog.com>
//
// 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 b... |
// 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 base
// Selector is a Warp10 selector
type Selector string
const (
// WildCardSelector select all available GTS
WildCardSelector Selector = "~.*{}"
)
// NewSelector Build a new Selector
func NewSelector(className string, labels Labels) Selector {
return Selector(className + formatLabels(labels))
}
|
package main
import "fmt"
type foo int
func main() {
var myAge foo = 44
fmt.Printf("%T \t %v \n", myAge, myAge)
var yourAge int
yourAge = 29
fmt.Printf("%T \t\t %v \n", yourAge, yourAge)
// this doesn't work :
// fmt.Println(myAge + yourAge) // not same type so can't add
// this conversion works :
// fm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.