text stringlengths 11 4.05M |
|---|
package basic
import (
"fmt"
"reflect"
"runtime"
)
// 可以返回多个值
func Div(a, b int) (int, int) {
return a / b, a % b
}
func Apply(op func(int, int) int, a, b int) int {
pointer := reflect.ValueOf(op).Pointer()
opName := runtime.FuncForPC(pointer).Name()
fmt.Printf("Calling function %s with args (%d, %d) \n", opN... |
package slaveMonitor
import (
"fmt"
"master/master"
"master/master/proxyMonitor"
"net"
"net/http"
"network"
"strings"
"time"
)
func ReceiveSlaveHeartbeat(request *http.Request, slaveMap map[string]master.Slave) (updatedSlaveMap map[string]master.Slave) {
slaveName, slaveAddress := processSlaveHeartbeatReques... |
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"runtime"
"strings"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
f, err := os.Open(fmt.Sprintf("%s/public%s", parentFilePathHelper(), r.URL.Path))
if err != nil {
w.WriteHeader(http.StatusInternalServe... |
package macro
import (
_ "github.com/micro/go-plugins/agent/command/animate"
_ "github.com/micro/go-plugins/agent/command/geocode"
_ "github.com/micro/go-plugins/agent/command/whereareyou"
_ "github.com/micro/go-plugins/broker/gocloud"
_ "github.com/micro/go-plugins/broker/googlepubsub"
_ "github.com/micro/go-pl... |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
numbers := []string{"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve"}
for {
if len(numbers) == 0 {
break
}
fmt.Printf("len(numbers) = %d ", len(numbers))
rand.Seed(time.Now().UnixNano())
i := rand.Intn(len(numb... |
// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
package watch
import (
"gopkg.in/fsnotify.v0"
"log"
"sync"
)
type InotifyTracker struct {
mux sync.Mutex
watchers map[*fsnotify.Watcher]bool
}
func NewInotifyTracker() *InotifyTracker {
t := new(InotifyTracker)
t.watchers = make(map[*f... |
package main
// https://leetcode-cn.com/problems/reorder-list/
func reorderList(head *ListNode) {
if head == nil || head.Next == nil {
return
}
slow := head
for fast := head; fast != nil && fast.Next != nil; {
fast = fast.Next.Next
slow = slow.Next
}
halfHead, half := &ListNode{}, slow.Next
slow.Next = ... |
/*
Copyright 2020 The Qmgo 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, sof... |
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package commitment
import (
"crypto"
"github.com/trustbloc/edge-core/pkg/log"
"github.com/trustbloc/sidetree-core-go/pkg/canonicalizer"
"github.com/trustbloc/sidetree-core-go/pkg/docutil"
"github.com/trustbloc... |
package common
import (
micro "github.com/micro/go-micro"
"github.com/micro/go-micro/client"
tracingWrapper "github.com/micro/go-plugins/wrapper/trace/opentracing"
opentracing "github.com/opentracing/opentracing-go"
"io"
"log"
"mix/test/utils/flags"
"mix/test/utils/trace"
)
var TracerCloser io.Closer
func in... |
// This file was generated for SObject LightningComponentResource, API Version v43.0 at 2018-07-30 03:48:05.787449968 -0400 EDT m=+52.132012535
package sobjects
import (
"fmt"
"strings"
)
type LightningComponentResource struct {
BaseSObject
CreatedById string `force:",omitempty"`
CreatedDate ... |
package client
import (
"reflect"
"testing"
)
func Test_strinifyEnv(t *testing.T) {
cases := []struct {
name string
input map[string]string
expect string
}{
{
name: "empty env",
input: map[string]string{},
expect: "",
},
{
name: "normal env",
input: map[string]string{
"CWD": "... |
package common
import "github.com/robertang/collector/cncf"
type MetricModule struct {
NewMetric func(config cncf.MetricConfig) Metric
}
type OutputModule struct {
NewOutput func(oc cncf.OutputConfig) Output
}
type Output interface {
Output(text interface{}) error
}
type Metric interface {
Collect(host strin... |
package gunit
import (
"bytes"
"io/ioutil"
"strings"
)
// lines cache
// fileName -> []line
type linesCache map[string][]string
func newLinesCache() linesCache {
rv := make(map[string][]string)
return linesCache(rv)
}
func (self linesCache) Put(fileName string) ([]string, error) {
lines, found := self[fileNam... |
/*
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, so... |
package base
import (
"bytes"
"io"
"io/ioutil"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type fakeOpError struct {
timeout bool
temporary bool
}
func (f fakeOpError) Error() string {
return "fake error"
}
func (f fakeOpError) Timeout() bool {
return f.timeout
}
func (f fakeOpError) Tempo... |
/*
Given a number between 1-26, return what letter is at that position in the alphabet. Return "invalid" if the number given is not within that range, or isn't an integer.
Examples
letterAtPosition(1) ➞ "a"
letterAtPosition(26.0) ➞ "z"
letterAtPosition(0) ➞ "invalid"
letterAtPosition(4.5) ➞ "invalid"
Notes
R... |
package main
import (
"fmt"
"runtime"
"sync"
)
const MAX int = 10
var (
counter int = 0
wg sync.WaitGroup
)
func Count(channel chan int) {
defer wg.Done()
count, ok := <- channel
if !ok {
return
}
value := count
runtime.Gosched()
value ++
count = value
... |
// package main
// import (
// "fmt"
// "os"
// "strconv"
// )
// level 3: doopprog
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args
if len(args) != 4 {
return
}
if args[2] != "+" && args[2] != "-" && args[2] != "/" && args[2] != "*" && args[2] != "%" {
fmt.Println(0)
re... |
package psql
import (
"TruckMonitor-Backend/dao"
"TruckMonitor-Backend/model"
"database/sql"
)
type psqlClient struct {
context PsqlContext
}
func ClientDao(context PsqlContext) dao.ClientDao {
return &psqlClient{context}
}
func (dao *psqlClient) db() *sql.DB {
return dao.context.GetDb()
}
func (dao *psqlCli... |
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
//type KongResult struct {
// Total int `json:"total"`
// Next int `json:"next"`
// Data []struct {
// StripURI bool `json:"strip_uri"`
// Name string `json:"name"`
// UpstreamURL string `js... |
// Package contextutil contains functions for working with contexts.
package contextutil
import (
"context"
"time"
)
type mergedCtx struct {
ctx1, ctx2 context.Context
doneCtx context.Context
doneCancel context.CancelFunc
}
// Merge merges two contexts into a single context.
func Merge(ctx1, ctx2 context.Co... |
package mc_pb
import (
"errors"
"io"
msgio "gx/ipfs/QmcxL9MDzSU5Mj1GcWZD8CXkAFuJXjdbjotZ93o371bKSf/go-msgio"
proto "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/proto"
mc "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec"
)
var Header []byte
var HeaderMsgio []byte
v... |
package keyboard
import tb "gopkg.in/tucnak/telebot.v2"
var (
EthButton = tb.ReplyButton{Text: "ETH"}
EtcButton = tb.ReplyButton{Text: "ETC"}
BtcButton = tb.ReplyButton{Text: "BTC"}
BchButton = tb.ReplyButton{Text: "BCH"}
LtcButton = tb.ReplyButton{Text: "LTC"}
SubscriptionStatus = tb.ReplyButton{Text: "Su... |
package user
import (
//For swagger
_ "go-mysql/docs"
"fmt"
"go-mysql/config"
"go-mysql/connection"
"go-mysql/customlogger"
"strconv"
)
//Order variables of struct must same with in table users and call body in postman
/*
== samples in post ==
{
"name": "Ferdian",
"age":29,
"location":"Indonesia"
... |
package tumblr
type ActivityEnvelope struct {
Id string `json:"id"`
Timestamp int64 `json:"timestamp"`
Version string `json:"version"`
ActivityPrivacy string `json:"activity_privacy"`
ActivityType string `json:"activity_type"`
Activity Activity `json:"activity"`
}
|
/*
Heading into the final day of regular season games for the 2023 NBA season, the fifth to ninth seeds in the Western Conference were still very undecided. Four games would determine the seeding:
New Orleans (N) at Minnesota (M)
Utah at LA Lakers (L)
Golden State (G) at Portland
LA Clippers (C) at Phoenix
Let the Bo... |
package utils
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
func StringToInt64(e string) (int64, error) {
return strconv.ParseInt(e, 10, 64)
}
func IntToString(e int) string {
return strconv.Itoa(e)
}
func Float64ToString(e float64) string {
... |
package syslog
import (
"bytes"
"errors"
"fmt"
"log"
"log/syslog"
"net"
"os"
"reflect"
"text/template"
"time"
"strings"
"github.com/gliderlabs/logspout/router"
)
var hostname string
func GetIndex(slice []string, value... |
package cache
import (
"context"
"strconv"
"sync"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/Juniper/contrail/pkg/models"
"github.com/Juniper/contrail/pkg/services"
)
const numEvent = 4
const timeOut = 10 * time.Second
func addWatcher(t *testing.T, w... |
package errorcode
// APIError API錯誤格式
type APIError struct {
Code string `json:"error_code"`
Text string `json:"error_text"`
}
// ErrorCode 錯誤代碼
func (e APIError) ErrorCode() string {
return e.Code
}
// ErrorText 錯誤訊息
func (e APIError) ErrorText() string {
return e.Text
}
// Error API錯誤訊息
func (e APIError) Erro... |
package distance
const (
CHEBYSHEV = "Chebyshev"
EUCLIDEAN = "Euclidean"
MANHATTAN = "Manhattan"
)
type req struct {
a, b []float64
}
func Get(a, b []float64, chs string) float64 {
r := req{
a: a,
b: b,
}
ln_a, ln_b := len(a), len(b)
r.Check(ln_a, ln_b)
switch chs {
case CHEBYSHEV:
return r.Chebysh... |
package twofer
//package main
import (
"fmt"
)
func ShareWith(name string) string {
if name=="" {
return "One for you, one for me."
}
var res string
res = "One for "+name+", one for me."
return res
}
func twofer() {
fmt.Println(ShareWith("Zaphod"))
}
|
package et
import (
"encoding/json"
"io/ioutil"
"sync"
)
type parsers struct {
sync.Mutex
items map[string]*Parser
}
func (p *parsers) get(fname string, refresh bool) (*Parser, error) {
p.Lock()
defer p.Unlock()
if !refresh && p.items[fname] != nil {
return p.items[fname], nil
}
content, err := ioutil.Re... |
package main
import (
"fmt"
"log"
"os"
"github.wtf/Brotchu/maze"
)
func main() {
maze, err := maze.LoadMaze(os.Args[1])
if err != nil {
log.Fatal(err)
}
fmt.Println(maze)
}
|
package k8sml
type Infrastructure interface {
GetID() string
GetVariableValue(variable string) interface{}
ExportModule() error
AddRuntimeVariable(key, value string)
GetRuntimeVariables() map[string]string
} |
// 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 problem1034
func colorBorder(grid [][]int, r0 int, c0 int, color int) [][]int {
if len(grid) == 0 {
return grid
}
oldColor := grid[r0][c0]
height := len(grid)
width := len(grid[0])
bfs(grid, r0, c0, height, width, oldColor, color)
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
if grid... |
package main
import (
"bytes"
"io"
"log"
"os"
"strconv"
"sync"
"time"
)
var pool = sync.Pool{
New: func() interface{} {
log.Println("allocation new bytes.Buffer")
return new(bytes.Buffer)
},
}
func main() {
var wg sync.WaitGroup
for i := 1; i < 20; i++ {
wg.Add(1)
customLog(os.Stdout, "debug-stri... |
package db
import (
"strconv"
"strings"
"time"
)
type InputDatetime struct {
year string
month string
date string
hour string
minute string
second string
}
func FormatDatetime(input *InputDatetime) string {
// Handle more faster
day := strings.Join([]string{input.year, input.month, input.date}, "-"... |
/*
* Copyright 2017 Manuel Gauto (github.com/twa16)
*
* 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 l... |
//comecando os estudos com o livro "A Linguagem de Progrmação Go"
//programa que imprime "Olá Mundo!"package hello_world
//go run nome_do_programa.go compila e executa o codigo
//go build nome_do_programa.go compila, cria um executavel e executa o codigo
package main
import "fmt"
func main() {
fmt.Println("Olá Mund... |
package rest
func setupNumbersRoutes(s *server) {
handler, err := loadNumbersHandler()
checkError(err)
s.router.GET("/numbers/:number/words", handler.ToWords)
}
|
/*
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the ... |
package main
import "testing"
func TestInput1(t *testing.T) {
res := part1(9, 25)
if res != 32 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput2(t *testing.T) {
res := part1(1, 48)
if res != 95 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput3(t *testing.T) {
res := part1(9, 48)
if res... |
package core
import (
"strings"
"github.com/golang/protobuf/ptypes"
mh "github.com/multiformats/go-multihash"
"github.com/textileio/go-textile/pb"
)
// AddComment adds an outgoing comment block
func (t *Thread) AddComment(target string, body string) (mh.Multihash, error) {
t.mux.Lock()
defer t.mux.Unlock()
i... |
package contexts
import (
"encoding/json"
"github.com/MerinEREN/iiPackages/datastore/context"
)
// ContextWithValueOnly is used for page context request's response body.
type ContextWithValueOnly struct {
Value string `json:"value"`
}
// GetLangValue returns context or contexts only with value of the correspondin... |
package main
import f "fmt"
func main() {
f.Println("패닉 복구")
printArray(1, 2, 3)
f.Println("Hello, World")
}
func printArray(a int, b int, c int) {
defer func() {
s := recover()
f.Println(s)
}()
array := [...]int{a, b, c}
for i := 0; i < 5; i++ {
f.Println(array[i])
}
}
|
package main
import (
"fmt"
)
func main() {
Mercado := []string{"Banana", "Arroz", "Feijão", "Tomate", "Frango", "Acucar"}
for lista := 0; lista < 6; lista++{
fmt.Printf("%d %s\n", lista, Mercado[lista])
}
}
|
package xcrypto
import (
"encoding/base64"
"encoding/hex"
)
type EncodeType uint
const (
ENCODE_UNSAFE_TYPE_RAW EncodeType = iota
ENCODE_SAFE_TYPE_BASE64
ENCODE_SAFE_TYPE_HEX
)
type Cipher struct {
encodeType EncodeType
}
func (c *Cipher) SetEncodeType(encodeType EncodeType) *Cipher {
c.encodeType = encodeT... |
// Copyright (c) 2017 Intel Corporation
//
// 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 ag... |
package redis
import (
"sync"
"time"
"github.com/dvirsky/go-pylog/logging"
"github.com/garyburd/redigo/redis"
"github.com/EverythingMe/meduza/driver"
"github.com/EverythingMe/meduza/errors"
"github.com/EverythingMe/meduza/query"
"github.com/EverythingMe/meduza/schema"
"golang.org/x/text/language"
)
// conne... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var TARGET int = 19690720
func main() {
handle, _ := os.Open("../resources/pwd-layers.txt")
defer handle.Close()
scanner := bufio.NewScanner(handle)
var pixels []int
width := 25
height := 6
for scanner.Scan() {
tmp := strings.Split(scanner... |
package goauth
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// testResourceOwnerPasswordGrant implements the ResourceOwnerPasswordGrant interface and
// is intended for use only in testing.
type testResourceOwnerPasswordGrant struct {
client *testClient
usern... |
package game_map
import (
"fmt"
"github.com/steelx/go-rpg-cgm/combat"
"github.com/steelx/go-rpg-cgm/world"
"math"
"reflect"
)
var CombatActions = map[world.Action]func(state *CombatState, owner *combat.Actor, targets []*combat.Actor, defI interface{}){
world.HpRestore: HpRestore,
world.MpRestore: MpResto... |
package match
import (
"fmt"
"gorm.io/gorm"
"match-go/app/model/mysql/common"
)
type SQL struct {
master *gorm.DB
table string
}
type Model struct {
ID uint64 `gorm:"primarykey"`
Name string `gorm:"type:varchar(255);default:'';not null;comment:比赛名称"`
Pic string `gorm:"type:varchar... |
package webrpc
import (
"net/http/httptest"
"net/url"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func makeTestServer() *httptest.Server {
i := 0
mutex := sync.RWMutex{}
globalnicks := map[string]struct{}{}
rpcserv := NewServer()
rpcserv.OnConn... |
package alerts
import (
"github.com/dennor/go-paddle/events/types"
"github.com/dennor/phpserialize"
"github.com/shopspring/decimal"
)
const PaymentDisputeClosedAlertName = "payment_dispute_closed"
// PaymentDisputeClosed refer to https://paddle.com/docs/reference-using-webhooks/#payment_dispute_closed
type Paymen... |
package operatorlister
import (
"fmt"
"sync"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/metadata/metadatalister"
)
// UnionCustomResourceDefinitionLister is a custom implementation of an CustomResourceDefinition lister that allows a new
// Lister to be regis... |
package main
import (
"context"
"errors"
"fmt"
"github.com/go-chi/chi"
"github.com/kreyyser/transshipment/common/config"
"github.com/kreyyser/transshipment/common/router"
"github.com/kreyyser/transshipment/restgateway/internal/ports"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"log"
"os"
"os/signal"
... |
package main
import (
"fmt"
"os"
"github.com/jessevdk/go-flags"
"github.com/contraband/gaol/commands"
)
type command struct {
name string
description string
command interface{}
}
func main() {
parser := flags.NewParser(&commands.Globals, flags.HelpFlag|flags.PassDoubleDash)
commands := []comma... |
package requestBody
type Message struct {
MsgContent string `json:"msg_content"`
Title string `json:"title,omitempty"`
ContentType string `json:"content_type,omitempty"`
Extras map[string]interface{} `json:"extras,omitempty"`
}
func (m *Message) SetMsgCo... |
// 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 oidcsdk
import (
"github.com/identityOrg/oidcsdk/util"
"strings"
)
type RequestProfile map[string]string
func NewRequestProfile() RequestProfile {
return make(map[string]string)
}
func (r RequestProfile) GetUsername() string {
return r["username"]
}
func (r RequestProfile) SetUsername(username string) ... |
package TriUI
import (
"strconv"
pf "trident.li/pitchfork/lib"
pu "trident.li/pitchfork/ui"
)
func h_group_vcp(cui pu.PfUI) {
criterias := []string{"Unmarked", "Dunno", "Vouched"}
limits := []int{10, 25, 50}
criteria, err := cui.FormValue("criteria")
if err != nil || (criteria != "Unmarked" && criteria != "Du... |
package main
import "fmt"
func main() {
fmt.Println(differenceOfDistinctValues([][]int{
{1, 2, 3},
{3, 1, 5},
{3, 2, 1},
}))
}
func differenceOfDistinctValues(grid [][]int) [][]int {
m, n := len(grid), len(grid[0])
ans := make([][]int, m)
for i := range ans {
ans[i] = make([]int, n)
}
abs := func(a i... |
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
)
// A Word refers to an N event (action or object).
type Word string
func (w Word) isNoun() bool {
re := "^[0-9]+$" // zero draft simplification
b, _ := regexp.MatchString(re, string(w))
return b
}
func (w Word) isVerb() bool {
re := "^[!#$%&*+,-;... |
/* RZFeeser | Alta3 Research
Writing out to a YAML file */
package main
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v3"
)
type User struct {
Name string
Occupation string
}
func main() {
users := map[string]User{"user 1": {"John Doe", "gardener"},
"user 2... |
package user
import (
"context"
"fmt"
"github.com/gorilla/mux"
"github.com/heptiolabs/healthcheck"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"net/http"
"runtime"
"time"
)
var getUserRequestsTotal prometheus.Gauge
var getUserRequestsError promet... |
package models
import (
"github.com/jinzhu/gorm"
"github.com/gophergala2016/source/core/foundation"
"github.com/gophergala2016/source/core/net/context/accessor"
)
// RootRepository is base struct for repository
type RootRepository struct {
Ctx foundation.Context
Orm *gorm.DB
}
// NewRootRepository creates new ... |
package config
import (
"fmt"
"os"
"strconv"
"time"
"github.com/DATA-DOG/go-sqlmock"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// Init returns connector to Soteria database
func NewMySQL() (*sqlx.DB, sqlmock.Sqlmock) {
var db *sqlx.DB
var mock sqlmock.Sqlmock
var err error
env := os... |
package main
import "fmt"
func main() {
items := []int{0, 1, 2, 1}
fmt.Println(items)
for i := 0; i < len(items); i++ {
if items[i] == 1 {
items = append(items, 10)
}
}
fmt.Println(items)
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/12/28 9:13 上午
# @File : lt_38_外观数列_test.go.go
# @Description :
# @Attention :
*/
package hot100
import (
"fmt"
"testing"
"time"
)
func Test_countAndSay(t *testing.T) {
fmt.Println(countAndSay(4))
}
func Test_Sleep(t *testing.T) {
ars := []int{1, 2, 3}
... |
package mira
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
// Short runes to variablize our types.
const (
submissionType = "s"
subredditType = "b"
commentType = "c"
redditorType = "r"
meType = "m"
)
func (c *Reddit) checkType(rtype ...string) (string, string, error) {... |
package certificate
import (
"io/ioutil"
"path"
"time"
"github.com/go-acme/lego/v3/certcrypto"
"github.com/urfave/cli/v2"
"github.com/alphatr/acme-lego/common"
"github.com/alphatr/acme-lego/common/bootstrap"
"github.com/alphatr/acme-lego/common/config"
"github.com/alphatr/acme-lego/common/errors"
"github.c... |
package main
import (
"go.uber.org/zap"
"testing"
)
func TestLogOut(t *testing.T) {
cfg := zap.NewProductionConfig()
cfg.OutputPaths = []string{
"./zap.log",
}
}
func TestLog(t *testing.T) {
//logger, _ := tests.NewProduction() // 生产环境
logger, _ := zap.NewDevelopment() // 开发环境
defer logger.Sync() ... |
// Copyright 2021 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 s3remote
import (
"io"
"path"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
type S3RemoteStore struct {
Bucket string
Root string
client *s3.S3
cfg *aws.Config
}
func (store *S3RemoteStore) GetMeta(name string) (strea... |
package database
import (
"context"
"errors"
"github.com/anshap1719/authentication/models"
"github.com/gofrs/uuid"
"github.com/mrjones/oauth"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"time"
)
var ErrTwitterAccountNotFound = errors.New("No TwitterAccount found in the database")
va... |
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
"ginTest/model"
"strconv"
)
func GetBillList(c *gin.Context) {
order, err := model.FindAllBill()
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"msg":"not find",
})
}
c.HTML(http.StatusOK,"billList.html",gin.H{
"data":order,
})
}
func GetBi... |
package main
import "fmt"
func main() {
var dazed = map[string]bool{
"Calisca": true,
"Heodan": true,
}
if dazed["Calisca"] {
fmt.Println("Calisca is dazed.")
}
// an empty struct as a sentinel
var charmed = map[string]struct{}{
"Calisca": struct{}{},
}
if _, ok := charmed["Heodan"]; ok {
fmt.Pr... |
package log
import (
"filemanager/constant"
"fmt"
"os"
"github.com/sirupsen/logrus"
)
// Log はログの本体です
var Log = logrus.New()
// SetLog はログの設定を行います。
func SetLog() {
if _, err := os.Stat(constant.LogFileName); err == nil {
err = os.Remove(constant.LogFileName)
}
errorLogFile, err := os.OpenFile(constant.Log... |
package client
import (
"errors"
"fmt"
"github.com/imroc/req"
)
func (c *AppDClient) CreateHealthRule(healthRule *HealthRule, applicationId int) (*HealthRule, error) {
resp, err := req.Post(c.createHealthRulesUrl(applicationId), c.createAuthHeader(), req.BodyJSON(&healthRule))
if err != nil {
return nil, err
... |
package game
import "go-mod/util"
// Draw function draws the updated pixels of Paddle to the screen as texture
func (p *Paddle) Draw(pixels []byte) {
startX, startY := p.X-p.W/2, p.Y-p.H/2
for y := 0; y < int(p.H); y++ {
for x := 0; x < int(p.W); x++ {
SetPixel(startX+float32(x), startY+float32(y), p.Color, p... |
// Copyright 2019 The OpenSDS 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 agre... |
package day1119test
import "strings"
/*
Go语言中的测试依赖go test命令,编写测试代码和编写普通的Go代码过程是类似的,不需要学习新的语法、规则或工具
在包目录内,所有以_test.go为后缀名的源代码文件都是go test测试的一部分,不会被go build编译到最终的可执行文件中去
在*_test.go文件中有三种类型的函数,单元测试函数、基准测试函数和示例函数
类型 格式 作用
测试函数 函数名前缀为Test 测试程序的一些逻辑行为是否正确
基准函数 函数名前缀为Benchmark 测试函数的性能
示例函数 函数名前缀为Exampl... |
package inspect
import (
"github.com/spf13/cobra"
kumactl_cmd "github.com/kumahq/kuma/app/kumactl/pkg/cmd"
"github.com/kumahq/kuma/app/kumactl/pkg/output"
kuma_cmd "github.com/kumahq/kuma/pkg/cmd"
)
func NewInspectCmd(pctx *kumactl_cmd.RootContext) *cobra.Command {
inspectCmd := &cobra.Command{
Use: "inspec... |
package remento
import (
"github.com/fncodr/godbase"
)
type Cx struct {
godbase.BasicCx
Settings Settings
user *User
}
func NewCx(db *Db) *Cx {
return new(Cx).Init(db)
}
func (self *Cx) Init(db *Db) *Cx {
self.BasicCx.Init(db)
self.Settings.Init(self)
return self
}
func (self *Cx) SetUser(u *User) {
s... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
)
type Player struct {
PlayerName string
CountryCode string
Skill int
OverallPoint float64
SelectedPercentage float64
PlayerValue float64
Score float64 `json:"-"`
}
... |
package main
import "fmt"
func producer(ch chan int) {
for n := 0; n<10; n++ {
ch<-n
}
close(ch)
}
func main() {
ch := make(chan int)
go producer(ch)
for v := range ch {
fmt.Println("Received", v)
}
}
|
/*
Generate protobuf go firstly by follow command in path igoexample/grpc/load_balancing/pb_echo:
protoc --proto_path=. --go_out=plugins=grpc:. ./*.proto
*/
package main
import (
"context"
"flag"
"github.com/fs714/igoexample/grpc/load_balancing/pb_echo"
"github.com/hashicorp/consul/api"
"github.com/satori/go.uui... |
package main
import (
"bufio"
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
)
func main() {
s := bufio.NewScanner(os.Stdin)
s.Scan()
t, _ := strconv.Atoi(s.Text())
for i := 0; i < t; i++ {
s.Scan()
n, _ := strconv.Atoi(s.Text())
chocs := make([]int, n)
s.Scan()
for i, v := range strings.Split(s.Te... |
/*
Many years ago after another unfruitful day in Cubicle Land, banging her head against yet another cutting edge, marketing buzzword-filled JavaScript framework, Janice the engineer looked out of the window and decided that time was ripe for a change.
So swapping her keyboard and mouse for a fork and a spade, she st... |
package server
import (
"bufio"
"compress/zlib"
"crypto/tls"
"encoding/binary"
"encoding/json"
"errors"
"io"
"log"
"net"
"sync"
"time"
"github.com/urso/go-lumber/v2/protocol"
)
type Server struct {
listener net.Listener
opts options
ch chan *Batch
done chan struct{}
wg sync.WaitGroup
}
type... |
package utils
import (
"errors"
"fmt"
"regexp"
)
func VaditationEmail(email string) error {
if email == "" {
return errors.New("email is required")
}
var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-... |
package hive
import (
"bufio"
"errors"
"sync"
"time"
"github.com/gosexy/to"
"github.com/tarm/serial"
"github.com/xiam/resp"
)
var (
ErrNilReply = errors.New(`Received a nil response.`)
ErrMaxReadAttemptsExceeded = errors.New(`Exceeded maximum read attempts.`)
)
var (
defaultTimeout = ti... |
package target
import (
"github.com/smallfish/simpleyaml"
"path/filepath"
"strings"
)
func GetStringArray(key string, data *simpleyaml.Yaml,
packageroot, curwd string) []string {
value := data.Get(key)
if value == nil {
return make([]string, 0)
}
value_arr, _ := value.Array()
string_array := make([]stri... |
package devto
import "strconv"
type RetrieveArticlesOption struct {
Page int
PerPage int
Tag string
Username string
State State
Top int
CollectionId int
}
type State string
const (
StateFresh State = "fresh"
StateRising = "rising"
StateAll = "all"
... |
// Copyright 2019 The bigfile Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrate
import (
"testing"
"github.com/bigfile/bigfile/config"
"github.com/bigfile/bigfile/databases"
"github.com/jinzhu/gorm"
"github.co... |
package internal
import (
"log"
"regexp"
"strings"
"time"
)
type WhoisResponseType int
const (
ResponseUnknown WhoisResponseType = iota
ResponseOk
ResponseError
ResponseAvailable
ResponseUnauthorized
ResponseExceededRate
)
func (wrt WhoisResponseType) String() string {
return [...]string{"Unknown", "OK",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.