text stringlengths 11 4.05M |
|---|
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package udp
import (
"bytes"
"github.com/iotaledger/wasp/packages/util"
"go.dedis.ch/kyber/v3"
"go.dedis.ch/kyber/v3/sign/bls"
)
type handshakeMsg struct {
netID string // Their NetID
pubKey kyber.Point // Our PubKey.
respond bool... |
package main
import (
"git.woa.com/trpc-go/helloworld/pkg/admin"
"github.com/gorilla/mux"
)
func Router(router *mux.Router, service *admin.Service) {
router.HandleFunc("/", service.Status).Methods("GET")
apiV1 := router.PathPrefix("/v1").Subrouter()
apiV1.HandleFunc("/users/{id}", service.QueryUsers).Methods("GE... |
package main
import (
"fmt"
"log"
"runtime"
"strings"
"github.com/go-gl/gl/v3.3-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
)
const windowWidth = 512
const windowHeight = 512
func init() {
// GLFW event handling must run on the main OS thread
runtime.LockOSThread()
}
func main() {
if err := glfw.Init(); er... |
package main
import (
"time"
"github.com/zc409/gostudy/day5/mylog"
)
func main() {
var log1 mylog.Minelog
for {
//log1 = mylog.Newloger("info")
//log1 = mylog.Newfileloger("info", "D:/gogo/src/github.com/zc409/gostudy/day5/homework_log/", "log.txt", 3*1024)
log1 = mylog.Melog("info", "f")
log1.Info("这是一个... |
package goidc
import (
"net/http/httptest"
"testing"
"time"
"github.com/lyokato/goidc/authorization"
"github.com/lyokato/goidc/basic_auth"
"github.com/lyokato/goidc/grant"
th "github.com/lyokato/goidc/test_helper"
)
func TestTokenEndpointAuthorizationCodePKCE(t *testing.T) {
te := NewTokenEndpoint("api.examp... |
package validator
import (
"crypto/ecdsa"
"crypto/rsa"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
"github.com/ory/fosite"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/oidc"
"github.com/authelia/authelia/v4/internal/utils"
)
// ValidateIdentityP... |
package cidenc
import (
"testing"
cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
mbase "gx/ipfs/QmekxXDhCxCJRNuzmHreuaT3BsuJcsjcXWNrtV9C8DRHtd/go-multibase"
)
func TestCidEncoder(t *testing.T) {
cidv0str := "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n"
cidv1str := "zdj7Wkkhxcu2rsiN6GUyHC... |
package tgo
import (
"fmt"
"strconv"
)
func UtilFloat64ToInt(value float64, multiplied float64) (intValue int, err error) {
aString := fmt.Sprintf("%.0f", value*multiplied)
intValue, err = strconv.Atoi(aString)
if err != nil {
UtilLogErrorf("%f to int failed,error:%s", value, err.Error())
}
return
}
|
package main
import "fmt"
var test = 1
func init() {
test++
fmt.Println("First init called.", test)
}
func init() {
test++
fmt.Println("Second init called.", test)
}
func main() {
test++
fmt.Println("Main function called.", test)
}
|
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2022 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 obta... |
package acoustid
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
hc "github.com/ocramh/fingerprinter/internal/httpclient"
fp "github.com/ocramh/fingerprinter/pkg/fingerprint"
)
const (
// AcoustIDBaseURL is the base URL used for queries the acoustid API
Acoust... |
package main
import "fmt"
// 方法
type dog struct {
name string
}
// 构造函数
func newDog(name string) dog {
return dog{
name,
}
}
//方法作用域特定类型的函数
//接受dog类型变量来调用,这里接受者是dog类型变量
//接受者表示的是调用该方法的具体类型变量,多用类型首字母表示(类似java this,python self)
func (d dog) wang() {
fmt.Printf("%s:汪汪汪\n", d.name)
}
func main() {
d1 := newDo... |
package handlers
import (
"net/http"
"github.com/Khigashiguchi/khigashiguchi.com/api/domain/entity"
"github.com/Khigashiguchi/khigashiguchi.com/api/infrastructure/repository"
"github.com/Khigashiguchi/khigashiguchi.com/api/interfaces/presenter"
"github.com/Khigashiguchi/khigashiguchi.com/api/usecase"
"github.co... |
package knapsackproblem01
import "testing"
func TestKnapsackProblem01(t *testing.T) {
type Knapsack struct {
w []int
v []int
c int
}
testData := []Knapsack{
Knapsack{
w: []int{1, 2, 3},
v: []int{6, 10, 12},
c: 5,
},
Knapsack{
w: []int{},
v: []int{},
c: 5,
},
}
expectedData := []i... |
package main
import "fmt"
func main() {
var age int //variable declaration
fmt.Println("My age is ", age) //uninitialised variables are assigned with default value zero
age = 10
fmt.Println("My age is ", age)
age++
fmt.Println("My age is ", age)
var superAge int = 20 //varibale with init... |
package main
import (
"fmt"
"github.com/bearname/videohost/internal/common/infrarstructure/mysql"
_ "github.com/go-sql-driver/mysql"
log "github.com/sirupsen/logrus"
"io/ioutil"
"os"
"path/filepath"
)
func main() {
var connector mysql.ConnectorImpl
err := connector.Connect("root", "123", "localhost:3306", "v... |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func increasingBST(root *TreeNode) *TreeNode {
if root==nil{return nil}
res :=[]int{}
res = iot(root, res)
head:=&TreeNode{Val: res[0]}
tmp := head
for i:=1;i<... |
/*
* @lc app=leetcode.cn id=1 lang=golang
*
* [1] 两数之和
*
* https://leetcode-cn.com/problems/two-sum/description/
*
* algorithms
* Easy (46.44%)
* Likes: 5960
* Dislikes: 0
* Total Accepted: 500.1K
* Total Submissions: 1.1M
* Testcase Example: '[2,7,11,15]\n9'
*
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组... |
package main
import (
_ "github.com/openshift-metal3/terraform-provider-ironic"
)
|
// https://tour.golang.org/concurrency/10
// This code shows a good example on how to wait
// until all chidren routines done
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, ... |
package models
import (
"encoding/json"
"io/ioutil"
"testing"
)
func BenchmarkCreateMe(b *testing.B) {
data, _ := ioutil.ReadFile("./tests/me.json")
meExampleJson := string(data)
for i := 0; i < b.N; i++ {
sub := Me{}
json.Unmarshal([]byte(meExampleJson), &sub)
}
}
|
package main
import (
"bufio"
"fmt"
"os/exec"
"strconv"
"sync"
"time"
"strings"
"github.com/vkorn/go-miio"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
"net/http"
"net/url"
)
const (
mac_start = 14
mac_end = 26
v_type_start = 66
v_type_end = 70
v_start = 70
v_end... |
package vsphere
import (
"net/netip"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/yaml"
machineapi "github.com/openshift/api/machine/v1beta1"
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/types/conversion"... |
package matematica
import "testing"
// Teste gerado pelo Go
func TestMedia(t *testing.T) {
t.Parallel()
type args struct {
numeros []float64
}
tests := []struct {
name string
args args
want float64
}{
// TODO: Add test cases.
{"teste 1", args{[]float64{7.2, 9.9, 6.1, 5.9}}, 7.28},
{"teste 2", args{... |
package render
import (
"net/http"
"testing"
"github.com/DungBuiTien1999/bookings/internal/models"
)
func TestAddDefaultData(t *testing.T) {
var td models.TemplateData
req, err := getSession()
if err != nil {
t.Error(err)
}
session.Put(req.Context(), "flash", "123")
result := AddDefaultData(&td, req)
i... |
package header
import "github.com/imulab/coldcall"
const (
KeyAccept = "KeyAccept"
)
// Accept sets the given contentType as the "KeyAccept" header on the http.Request.
func Accept(contentType string) coldcall.Option {
return Custom(KeyAccept, contentType)
}
|
package main
import (
"fmt"
)
// 429. N叉树的层序遍历
// 给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
// https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
func main() {
tree := &Node{
Val: 1,
Children: []*Node{
{3, []*Node{
{5, nil},
{6, nil},
}},
{2, nil},
{4, nil},
},
}
fmt.Println(l... |
package subprocess
import (
"context"
"fmt"
"log"
"os/exec"
"github.com/egnyte/ax/pkg/backend/common"
"github.com/egnyte/ax/pkg/backend/stream"
)
type SubprocessClient struct {
command []string
}
func (client *SubprocessClient) ImplementsAdvancedFilters() bool {
return true
}
func (client *SubprocessClient... |
package logger
import (
"github.com/op/go-logging"
"os"
)
const (
OUTPUT_STD = "stdout"
OUTPUT_FILE = "file"
OUTPUT_BOTH = "both"
)
var Log *logging.Logger
func InitLogger(category string, output string, logfile string) {
//create a
Log = logging.MustGetLogger(category)
//define formater
var format = logg... |
package podstatus
import (
"testing"
"github.com/square/p2/pkg/store/consul/statusstore"
"github.com/square/p2/pkg/store/consul/statusstore/statusstoretest"
"github.com/square/p2/pkg/types"
)
func TestSetAndGetStatus(t *testing.T) {
store := newFixture()
processStatus := ProcessStatus{
EntryPoint: "echo_s... |
package crawler
type TreeNode struct {
Text string `json:"text,omitempty"`
Nodes []TreeNode `json:"nodes,omitempty"`
}
func (t *TreeNode) Add(node TreeNode, indexes []int) {
if len(indexes) > 0 {
i := indexes[0]
for len(t.Nodes) <= i {
t.Add(TreeNode{}, []int{})
}
t.Nodes[i].Add(node, indexes[1:])
... |
package gui
import "github.com/jesseduffield/lazydocker/pkg/gui/panels"
func (gui *Gui) intoInterface() panels.IGui {
return gui
}
|
package main
import "fmt"
func main() {
/**
Print 无换行,不可读取变量,需使用\n进行换行
Println 有换行,不可读取变量
Printf 无换行,可以读取变量,需使用\n进行换行
*/
a1 := 1
fmt.Println("这个数字为:%d",a1)
fmt.Printf("这个数字为:%d",a1)
fmt.Printf("这个数字为:%d\n",a1)
fmt.Print("这个数字为:%d",a1)
fmt.Print("这个数字为:%d\n",a1)
fmt.Println(`用这个符号
你怎么输入的
它怎么输... |
package app
import (
"golang.org/x/net/context"
"github.com/sirupsen/logrus"
"github.com/docker/libcompose/cli/app"
"github.com/docker/libcompose/cli/command"
"github.com/docker/libcompose/cli/logger"
"github.com/docker/libcompose/lookup"
"github.com/docker/libcompose/project"
"github.com/docker/libcompose/pr... |
package functions
// Top will return n elements from head of the slice
// if the slice has less elements then n that'll return all elements
// if n < 0 it'll return empty slice.
func (ss SliceType) Top(n int) (top SliceType) {
for i := 0; i < len(ss) && n > 0; i++ {
top = append(top, ss[i])
n--
}
return
}
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
const cacheDir string = "./xkcdcache"
type ComicInfo struct {
Month string
Num int
Link string
Year string
News string
SafeTitle string `json:"safe_title"`
Transcript string
Alt string
Img ... |
package goreq
import (
"fmt"
"github.com/stretchr/testify/assert"
"net/http"
"net/url"
"testing"
)
func TestRawResp(t *testing.T) {
var resp http.Response
var bodyBytes []byte
err := Get("https://httpbin.org/get", RawResp(&resp, &bodyBytes)).Do()
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.St... |
package model
import (
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"strings"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/google/uuid"
"gopkg.in/yaml.v3"
)
const (
attestationTypeFIDOU2F = "fido-u2f"
)
// WebAuthnUser is an o... |
/*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package swagger
// ally object
type GetWarsWarIdAlly struct {
// Alliance ID if and only if this ally is an alliance
AllianceId int32 `json... |
package common
import (
"encoding/json"
"fmt"
"github.com/garyburd/redigo/redis"
"time"
)
type RedisConfig struct {
Host string `json:"host"`
Port int32 `json:"port"`
MaxIdle int32 `json:"max_idle"`
IdleTimeout int32 `json:"idle_timeout"`
MaxActive int32 `json:"max_activ... |
package db
import (
. "gopkg.in/check.v1"
"testing"
)
// IF USING test framework, need a file like this in each package=directory.
func Test(t *testing.T) { TestingT(t) }
type XLSuite struct{}
var _ = Suite(&XLSuite{})
const (
BLOCK_SIZE = 4096
SHA1_LEN = 20
SHA3_LEN = 32
VERBOSITY = 1
)
|
package main
func reverseKGroup(head *ListNode, k int) *ListNode {
dummyHead := &ListNode{}
dummyHead.Next = head
pre := dummyHead
cur := head
next := &ListNode{}
len := 0
for head != nil {
len++
head = head.Next
}
head = dummyHead.Next
//1->2->3 先反转成2->1->3 载反转成3->2-1,此时相当于2-1是一个整体
for i := 0; i < len... |
package config
import (
"github.com/caarlos0/env"
"log"
)
type CommonEnvConfigs struct {
// Logging level
LogLevel string `json:"LOG_LEVEL" env:"LOG_LEVEL" envDefault:"debug"`
// Service configs
ServiceName string `json:"SERVICE_NAME" env:"SERVICE_NAME" envDefault:"vk-scrapper"`
// Server configs
ServerPort... |
package models
import (
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"log"
"net/url"
)
const (
XINSEHNG_URL_PREFIX = "http://xinsheng.huawei.com/cn/index.php?app=search&mod=Forum&act=index&cTime=1&key="
)
type ForumInfo struct {
Title string `json:"title"`
Href string `json:"href"`
Info string `... |
package main
import (
"fmt"
"math/big"
)
func main() {
var n int
fmt.Scanf("%d", &n)
for i := 0; i < n; i++ {
var x int64
_, err := fmt.Scanf("%d", &x)
if err != nil {
break
}
x++
if x%2 == 0 || x%7 != 0 {
fmt.Println("No")
continue
}
i := big.NewInt(x + 2)
isPrime := i.ProbablyPr... |
// fzfutil is to use fzf as library
package fzfutil
import (
"io"
"os"
"os/exec"
"strings"
)
// Based on, https://junegunn.kr/2016/02/using-fzf-in-your-program
func FZF(input func(in io.WriteCloser), opts ...string) ([]string, error) {
fzf, err := exec.LookPath("fzf")
if err != nil {
return nil, err
}
cmd ... |
package autonat
import (
"context"
"net"
"testing"
"time"
pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore"
libp2p "gx/ipfs/QmSgtf5vHyugoxcwMbyNy6bZ9qPDDTJSYEED2GkWjLwitZ/go-libp2p"
manet "gx/ipfs/QmZcLBXKaFe8ND5YHPkJRAwmhJGrVsi1JqDZNyJ4nRK5Mj/go-multiaddr-net"
autonat "gx/ip... |
package neo
import (
"github.com/jmcvetta/neoism"
"github.com/yggie/github-data-challenge-2014/models"
)
func PersistPushEvent(event *models.PushEvent) error {
queries := make([]*neoism.CypherQuery, 0)
if !CheckExists(EVENTS, event.Id) {
query := neoism.CypherQuery{
Statement: `CREATE (:` + string(EVENTS) +... |
package game
import (
"github.com/tanema/amore/gfx"
)
var colors = map[string]*gfx.Color{
"sky": gfx.NewColor(114, 215, 238, 255),
"tree": gfx.NewColor(0, 81, 8, 255),
"fog": gfx.NewColor(0, 81, 8, 255),
"road": gfx.NewColor(107, 107, 107, 255),
"grass": gfx.NewColor(16, 170, 16, 255),
"rumble": gfx... |
//go:generate goagen bootstrap -d goabinsample/design
package main
import (
"goabinsample/app"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
)
func main() {
// Create service
service := goa.New("binsample")
// Mount middleware
service.Use(middleware.RequestID())
service.Use(middleware.Lo... |
// vi:nu:et:sts=4 ts=4 sw=4
// See License.txt in main repository directory
// Handle HTTP Events
// Generated: 2019-04-24 11:09:33.44631 -0400 EDT m=+0.001906926
package handlers
import (
_ "github.com/2kranki/go-sqlite3"
"html/template"
)
var Tmpls *template.Template
func Title(i interface{}) string... |
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"os"
"os/exec"
"raft"
"strconv"
"strings"
//"sync"
"testing"
"time"
)
var noOfThreads int = 50
var noOfRequestsPerThread int = 10
//var wgroup sync.WaitGroup
var commands []string
var procmap map[int]*exec.... |
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package operationparser
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/trustbloc/sidetree-core-go/pkg/api/operation"
"github.com/trustbloc/sidetree-core-go/pkg/docutil"
internal "github.co... |
/*
Package storagecache provides a mechanism for using various storage as datastore's cache.
This package will not be used directly, but it will be used via aememcache or redicache.
This package automatically processes so that the cache state matches the Entity on Datastore.
The main problem is transactions.
Do not r... |
package modules
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/sirupsen/logrus"
)
// NotificationController operations for Notification
type NotificationController struct {
BaseUserController
}
// PostMessage ...
// @Title PostMessage
// @Description create Notification
// @Success 204
// @Failure... |
package logger
import (
"go.uber.org/zap"
"testing"
)
func TestLogger(t *testing.T) {
cfg := new(LogConfig)
cfg.Develop = true
cfg.Level = "debug"
cfg.Path = "./test.log"
cfg.ErrorPath = "./test-error.log"
log := NewRotateLogger(*cfg)
defer log.Sync()
log.Debug("debug", zap.String("aaa", "bbb"), zap.Strin... |
package user
import (
"fmt"
"github.com/btnguyen2k/prom"
"main/src/gvabe/bo"
"github.com/btnguyen2k/henge"
)
// NewUserDaoSql is helper method to create SQL-implementation of UserDao.
func NewUserDaoSql(sqlc *prom.SqlConnect, tableName string) UserDao {
dao := &UserDaoSql{}
dao.UniversalDao = henge.NewUnivers... |
package main
func main() {
addFunc := func(terms ...int) (numTerms int, sum int) {
for _, term := range terms {
sum += term
}
numTerms = len(terms)
return
}
x, y := addFunc(1, 2, 3, 4, 5 ,6)
println(x, y)
}
|
//go:build go1.15
// +build go1.15
package time
import (
"sync"
"time"
)
var tickerPool = sync.Pool{}
// AcquireTicker returns a ticker from the pool if possible.
func AcquireTicker(d time.Duration) *time.Ticker {
v := tickerPool.Get()
if v == nil {
return time.NewTicker(d)
}
t, ok := v.(*time.Ticker)
if ... |
package utils
import (
"fmt"
"os"
"time"
log "github.com/sirupsen/logrus"
)
// configure logging using env variables
func ConfigureLogging() {
InitLogging(log.DebugLevel)
strlevel := Getenv("LOG_LEVEL", "TRACE")
level := parseLogLevel(strlevel)
log.SetLevel(level)
style := os.Getenv("LOG_STYLE")
if style =... |
package main
import (
"fmt"
"os"
"io"
"io/ioutil"
"path"
"strings"
"log"
"crypto/md5"
"encoding/hex"
)
func main() {
filepath := "E:\\"
files, err := ioutil.ReadDir(filepath)
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.... |
package vcs
import (
"net/http"
"os"
"sync"
"github.com/sirkon/goproxy/internal/errors"
"github.com/sirkon/goproxy"
"github.com/sirkon/goproxy/internal/modfetch"
)
// plugin creates source for VCS repositories
type plugin struct {
rootDir string
// accessLock is for access to inWork
accessLock sync.Locker... |
package elemental
import (
"context"
"errors"
"fmt"
"time"
"github.com/Nv7-Github/Nv7Haven/pb"
"google.golang.org/protobuf/types/known/emptypb"
)
func (e *Elemental) CreateSugg(_ context.Context, req *pb.CreateRequest) (*emptypb.Empty, error) {
suc, msg := e.CreateSuggestion(req.Mark, req.Pioneer, req.Elem1, ... |
package byopenwrt
import (
"bylib/byhttp"
"bylib/bylog"
"bylib/byutils"
"fmt"
"github.com/go-cmd/cmd"
"github.com/pkg/errors"
"os"
"os/signal"
"strings"
"syscall"
)
type SysAdmin struct{
UploadFlag bool
}
//获取系统时间
func (s *SysAdmin)getSysTime(ctx *byhttp.MuxerContext)error {
dt:=byutil.OpDateTime{
}
i... |
package entities
// User defines a user in the program.
type User struct {
Name string
email string
}
|
package slackbot
import (
"context"
"log"
"time"
)
const maxErrors = 3
const tickDuration = 20 * time.Second
// 1m20s
const monitorErrorMarginDuration = (maxErrors + 1) * tickDuration
// Monitor polls Cloud Build until the build reaches completed status, then triggers the Slack event.
func Monitor(ctx context.Con... |
package main
import "fmt"
func main() {
ch :=GenerateNatural() // 自然数序列 2,3,4
for i:=0;i<100;i++ {
prime :=<-ch // 新出现的素数
fmt.Printf("%v: %v\n",i+1,prime)
ch =PrimeFilter(ch,prime) // 基于新素数构造的过滤器
}
}
//返回生成自然数序列的channel 2,3,4,5,...
func GenerateNatural() chan int {
ch :=make(chan int)
go func() {
fo... |
package main
import (
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/hyperorchidlab/go-miner-pool/account"
com "github.com/hyperorchidlab/go-miner-pool/common"
"github.com/hyperorchidlab/go-miner/node"
"github.com/spf13/cobra"
"io/ioutil"
"os"
"path/filepath"
)
var InitCmd = &cob... |
/*
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the ... |
package main
import (
"fmt"
"encoding/json"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
// ============================================================
// initVote - create a new vote and store into chaincode state
// ========================================... |
/*
Copyright 2018 Planet Labs 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, software
di... |
package model
import (
"gorm.io/gorm"
"time"
)
const OrderNotifyLogTableName = "order_notify_log"
const (
// 通知状态
OrderNotifyStatusNotifying = 0 // 通知中
OrderNotifyStatusSuccess = 1 // 成功
OrderNotifyStatusFail = 2 // 失败
// 通知日志订单类型
NotifyLogOrderTypePay = 1 // 代收订单
NotifyLogOrderTypeTransfer = 2... |
// Copyright 2016-2021, Pulumi Corporation.
package schema
import (
"fmt"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"math"
"strings"
)
type ValidationFailure struct {
Path s... |
package main
import (
"fmt"
)
func main() {
// Print
a := 10
fmt.Print("Um print sem quebra de linha")
fmt.Println("Um print com quebra de linha")
fmt.Printf("Um print com formatação. a = %v\n", a)
// Sprint (String Print)
b := "Olá"
c := "Tudo bem com vc?"
sprint1 := fmt.Sprint(b, c)
sprint2 := fmt.Spr... |
package main
import (
"fmt"
)
// 两整型相加
func add(a, b int) (result int) {
result = a + b
return
}
// 两整型相减
func minus(a, b int) (result int) {
result = a - b
return
}
// 定义了一个两参数都整型,同时返回值也是整型的函数类型FuncTest
type FuncTest func(int, int) int
func main() {
var funcTest FuncTest
// 将加法函数赋值给funcTest
funcTest = ad... |
package xendit
import (
"github.com/imrenagi/go-payment"
"github.com/imrenagi/go-payment/subscription"
)
// NewStatus convert xendit status string to subscripiton status
func NewStatus(s string) subscription.Status {
switch s {
case "ACTIVE":
return subscription.StatusActive
case "PAUSED":
return subscriptio... |
package twitterscraper
import (
"testing"
)
func TestGetTrends(t *testing.T) {
trends, err := GetTrends()
if err != nil {
t.Error(err)
}
if len(trends) != 10 {
t.Error("Expected 10 trends")
}
}
|
package config_test
import (
"bytes"
"encoding/json"
"reflect"
"testing"
. "github.com/andygrunwald/perseus/config"
)
func unitTestJSONContent() []byte {
b := bytes.NewBufferString(`{
"archive": {
"directory": "dist",
"format": "tar",
"prefix-url": "http://my.url.com/packages/",
... |
package main
import "fmt"
var slice []byte
func main() {
slice = make([]byte, 12)
go func() {
slice[0] = byte('H')
}()
slice[3] = byte('e')
fmt.Println(slice)
}
|
package mtest
import (
"encoding/json"
"os"
"strconv"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("assets", func() {
It("should work as expected", func() {
f := localTempFile("test")
defer os.Remove(f.Name())
By("Uploading an asset")
sabactl("assets", "upload", "test", f.... |
package posts
import (
"appointy/dbservice"
"context"
"sync"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var getPostLock sync.Mutex
func GetPost(id string) Post {
getPostLock.Lock()
defer getPostLock.Unlock()
var post Post
client, _ := dbservice.GetMongoClient()
var p... |
package swarm
import (
"io"
"net"
"sync"
"time"
"xd/lib/bittorrent"
"xd/lib/bittorrent/extensions"
"xd/lib/common"
"xd/lib/log"
)
const DefaultMaxParallelRequests = 2
// a peer connection
type PeerConn struct {
inbound bool
closing bool
c net.Conn
id ... |
package hot100
import (
"fmt"
"testing"
"time"
)
func Test_permute(t *testing.T) {
fmt.Println(permute([]int{1, 2, 3}))
}
func Test_asssd(t *testing.T) {
d := make(chan int, 10)
go func() {
d <- 1
d <- 2
}()
go func() {
for v := range d {
fmt.Println(v)
}
}()
time.Sleep(time.Second*2)
d<-33
ti... |
package middleware
import (
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"net/http"
"server-monitor-admin/global"
"server-monitor-admin/global/response"
"server-monitor-admin/utils"
"strconv"
)
func JwtAuth() gin.HandlerFunc {
return func(context *gin.Context) {
auth := context.Request.Header.Ge... |
package util
import (
"strings"
)
const notationChars = "BCDGHIJKLMNOPQRSTUVXYZ"
func Num2Char(num int) string {
out := &strings.Builder{}
encodeNum(num, out)
return out.String()
}
func encodeNum(num int, out *strings.Builder) {
if num/len(notationChars) != 0 {
encodeNum(num/len(notationChars), out)
}
out.... |
package handlers
import (
"forum/internal/handlers/backend"
"github.com/gin-gonic/gin"
)
func backendRouter(r *gin.RouterGroup) {
r.GET("/welcome", backend.Hello)
}
|
package sheet_logic
import (
"hub/sheet_logic/sheet_logic_types"
"testing"
)
func TestIntModulo(t *testing.T) {
uut := NewIntModulo(variableName)
grammarElementScenario(t, uut.GrammarElement, sheet_logic_types.IntModulo)
uut.SetLeftArg(NewIntConstant(variableName, 5))
uut.SetRightArg(NewIntConstant(variableNam... |
/*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package swagger
import (
"time"
)
// 200 ok object
type GetCharactersCharacterIdOk struct {
// The character's alliance ID
AllianceId int... |
package main
import "fmt"
func editMap(m map[int]int) {
m[3] = 8
m[4] = 9
}
func editSlice(s []int) {
s = append(s, 5)
s = append(s, 9)
}
func main() {
m := make(map[int]int, 0)
m[1] = 5
m[2] = 3
fmt.Printf("%v\n", m)
editMap(m)
fmt.Printf("%v\n", m)
s := make([]int, 2)
s[0] = 2
s[1] = 5
fmt.Printf("... |
// Copyright 2013 Benjamin Gentil. All rights reserved.
// license can be found in the LICENSE file (MIT License)
package zlang
import (
"fmt"
)
func runTest(name, src string) {
l := NewLexer(name, src)
for {
it := l.NextItem()
fmt.Println(it.Token, "\t\t", it)
if it.Token == TOK_EOF || it.Token == TOK_ERROR... |
package terminfo
var rxvtUnicode = Terminfo{
Name: "rxvt-unicode",
Keys: [maxKeys]string{
"",
"\x1b[11~",
"\x1b[12~",
"\x1b[13~",
"\x1b[14~",
"\x1b[15~",
"\x1b[17~",
"\x1b[18~",
"\x1b[19~",
"\x1b[20~",
"\x1b[21~",
"\x1b[23~",
"\x1b[24~",
"\x1b[2~",
"\x1b[3~",
"\x1b[7~",
"\x1b[8~",
... |
package main
import (
"fmt"
"time"
context "golang.org/x/net/context"
)
func test() {
gen := func(ctx context.Context) <-chan int {
dest := make(chan int, 3)
n := 1
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("ordered to stop")
return
case dest <- n:
fmt.Printf("... |
package clientserverpair
import (
"bytes"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
func newConnPair(bufSize int) (*pipeConn, *pipeConn) {
b1 := bytes.NewBuffer(make([]byte, 0, bufSize))
b2 := bytes.NewBuffer(make([]byte, 0, bufSize))
var b1Mu, b2Mu sync.Mutex
pc1 := &pipeConn{
cToS: b1,
cToSMu: &b1Mu... |
package pipeline
import (
"context"
"encoding/base64"
"fmt"
)
//Encode 는 in 에서 일반 텍스트를 입력받아
//"입력 문자열" => <base64 인코딩된 문자열>을 out 에 쓴다.
func (w *Worker) Encode(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case val := <-w.in:
w.out <- fmt.Sprintf("%s => %s", val, base64.StdEncoding.En... |
package timeformat
import (
"strings"
"time"
)
var (
lm = []string{
"YYYY", "2006",
"YY", "06",
"MMMM", "January",
"MMM", "Jan",
"MM", "01",
"M", "1",
"DD", "02",
"D", "2",
"hh", "03",
"HH", "15",
"h", "3",
"wwww", "Monday",
"www", "Mon",
"mm", "04",
"m", "4",
"ss", "05",
"s", "5"... |
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
//os.O_WRONLY | os.O_TRUNC:只写方式打开并且清空
//file, err := os.OpenFile("F:/go/src/golangStudy/file_opt/you.txt", os.O_WRONLY|os.O_TRUNC, 0666)
//os.O_WRONLY | os.O_TRUNC:只写方式打开并且追加
//file, err := os.OpenFile("F:/go/src/golangStudy/file_opt/you.txt", os.O... |
package aliyun
import (
"os"
"path"
)
// inject neccessary AliIndex.class for aliyun function
func (m* Manager) createJava8Function(dir string) error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
// TODO: config
err = os.Link(path.Join(home, ".jfManager", "ali", "java8", "AliIndex.class") ,pa... |
package main
import (
"os"
"os/exec"
"strings"
"github.com/matti/fixer"
)
func main() {
prefixer := fixer.Fixer{
Writer: os.Stdout,
PrefixFunc: func(s string) string {
return "pinging "
},
InfixFunc: func(s string) string {
if len(s) > 25 {
return "< " + s[:25] + " ... >"
}
return "< ... |
package main
import (
"net/http"
"github.com/GoGroup/Movie-and-events/cinema/repository"
"github.com/GoGroup/Movie-and-events/cinema/service"
"github.com/GoGroup/Movie-and-events/cinev_park/http/handler"
usrvim "github.com/GoGroup/Movie-and-events/hall/repository"
urepim "github.com/GoGroup/Movie-and-events/hal... |
package main
import "fmt"
func main() {
m := make(map[string]int)
changeMe(m)
fmt.Println(m["Shikamaru"]) // 10
}
func changeMe(z map[string]int) {
z["Shikamaru"] = 10
}
/*
Allocation with make
Back to allocation. The built-in function make(T, args)
serves a purpose different from new(T). It creates slices, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.