text stringlengths 11 4.05M |
|---|
package cache
import (
"testing"
"time"
"github.com/gomodule/redigo/redis"
)
func DoTestCache(t *testing.T, c Cache) {
// not found
if v, err := c.Get("a"); v != nil || err != NotFound {
t.Error(err, "should value nil and err not found")
}
time.Sleep(time.Millisecond)
if v, err := c.Get("a"); v != nil || e... |
package main
import (
"github.com/codegangsta/cli"
)
func NewHostCommand() cli.Command {
return cli.Command{
Name: "host",
Usage: "Operations with vulcan hosts",
Subcommands: []cli.Command{
{
Name: "add",
Flags: []cli.Flag{
cli.StringFlag{"name", "", "hostname"},
},
Usage: "Add a new... |
package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main() {
connect, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
fmt.Println("connect redis err:", err)
return
}
defer connect.Close()
_, err = connect.Do("HSet", "books", "abc", 100)
if err != nil {
fmt.Println("set err:... |
package clog
import (
"io"
)
type Topic struct {
name string
config TopicConfig
log *Log
writer *io.Writer
}
func newTopic(config TopicConfig) *Topic {
return &Topic{}
}
|
package utils
import (
"bytes"
"fmt"
"os"
"strings"
"text/template"
"github.com/docker/go-units"
"github.com/urfave/cli/v2"
corepb "github.com/projecteru2/core/rpc/gen"
)
// GetNetworks returns a networkmode -> ip map
func GetNetworks(network string) map[string]string {
var ip string
networkInfo := string... |
package main
// TODO: handle erors properly
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
func main() {
// get the port heroku assignened for us
port := os.Getenv("PORT")
if port == "" { // ....if heroku didn't give us a port (DEBUG)
port = "8080"
}
// set up default path
http.HandleFunc... |
// Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package gohttp
import (
"errors"
"net/http"
)
func (c *httpClient) do(method, url string, headers http.Header, body interface{}) (*http.Response, error) {
client := http.Client{}
request, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, errors.New("unable to create a request")
}
fullHe... |
package main
import (
"bufio"
"flag"
"fmt"
"os"
"github.com/Shopify/sarama"
)
// producer kafka
func Producer() {
addr := flag.String("kafka_addr", "", "kafka_addr")
topic := flag.String("kafka_topic", "", "kafka_topic")
flag.Parse()
if len(*addr) == 0 || len(*topic) == 0 {
panic(`please input params ex... |
/*
* @lc app=leetcode.cn id=207 lang=golang
*
* [207] 课程表
*/
package main
import (
"fmt"
)
/*
// DFS
// 0表示没访问
// 1表示当前dfs访问过
// 2表示其他dfs分支访问过
func canFinish(numCourses int, prerequisites [][]int) bool {
var (
edges = make([][]int, numCourses)
visited = make([]int, numCourses)
result... |
package main
import (
"bufio"
"encoding/binary"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"log"
"os"
)
type ProcessorPool struct {
Pool chan chan string
maxWorkers int
}
var ProcessQueue chan string
type Processor struct {
Pool chan chan string
ProcessChannel chan string
quit ... |
package main
import (
"fmt"
"os"
"os/exec"
"time"
)
// Terminal size
const (
WIDTH = 10
HEIGHT = 5
)
func getCell(board []int, x int, y int) int {
if x < 0 || x > WIDTH {
return 0
} else if y < 0 || y > HEIGHT {
return 0
}
return board[x+(y*WIDTH)]
}
// Since i am using integers to represent alive ( ... |
// Package evaluator contains the core of our interpreter, which walks
// the AST produced by the parser and evaluates the user-submitted program.
package evaluator
import (
"bytes"
"fmt"
"math"
"os"
"os/exec"
"regexp"
"strings"
"github.com/kasworld/nonkey/config/builtinfunctions"
"github.com/kasworld/nonkey... |
package main
import (
"github.com/hardstylez72/bblog/internal/auth"
"github.com/hardstylez72/bblog/internal/objectstorage"
"github.com/spf13/viper"
)
const (
cfgAllData = ""
)
type Config struct {
Port string
Env string
Host string
Oauth auth.Oauth
Databases Databases
ObjectStorage
Ses... |
package epistoli
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/oz/miniporte/link"
)
const (
// ServiceName is this package's pretty name.
ServiceName = "epistoli"
// APIURL is the base API endpoint for Epistoli.
APIURL = "https://episto.li/api/v1"
// HT... |
/*
Copyright 2019 The Knative 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 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
package main
import (
"fmt"
"strconv"
)
func main() {
n := 103456789
numStr := strconv.Itoa(n)
isNonZero := false
for i := len(numStr) - 1; i >= 0; i-- {
if isNonZero && string(numStr[i]) == "0" {
fmt.Println("true")
return
}
if string(numStr[i]) != "0" {
isNonZero = true
}
}
fmt.Printl... |
package marathon
import (
"encoding/json"
"io/ioutil"
"net/http"
)
// Error is a trivial implementation of error
type Error struct {
message string `json:"message"`
}
// Error returns the description of the error
func (e *Error) Error() string {
return e.message
}
func parseError(resp *http.Response) error {
... |
package main
import "fmt"
func main() {
var str1 string //声明变量
str1 = "abc" //赋值
fmt.Println(str1)
//自动推导类型
str2 := "知了课堂"
fmt.Println(str2)
fmt.Printf("%T\n",str2)
//ch := 'a'
//str := "a" //'a''\0' 字符串结束标志
//len函数 计算字符串中字符的个数 不包含\0
//在go语言中 一个汉字占3个字符
fmt.Println(len(str2))
//字符串拼接 +
st... |
/*
* @lc app=leetcode.cn id=1436 lang=golang
*
* [1436] 旅行终点站
*/
// @lc code=start
package main
func destCity(paths [][]string) string {
pathMap := make(map[string]bool)
for i := 0; i < len(paths); i++ {
pathMap[paths[i][0]] = true
}
for _, path := range paths {
if !pathMap[path[1]] {
return path[1]
... |
package main
import (
"log"
"math"
)
//链表实现多项式的求和.本来是做多项式求和的,这里写的是指数式求和
type PNode struct{
coef float64
expn float64
belong *PolymomialList
next *PNode
}
type PolymomialList struct{
root PNode
length int
last *PNode
}
func (l *PolymomialList)Init() *PolymomialList{
l.length = 0
l.root.next = nil
l.la... |
package ghosts
type Ghost interface {
Name() string
Evidence() [3]string
}
|
package tfc
import (
"testing"
tfcPb "github.com/stefanprisca/strategy-protobufs/tfc"
"github.com/stretchr/testify/require"
)
func TestGenerateGameBoard(t *testing.T) {
gb, err := NewGameBoard()
require.NoError(t, err)
assertGameBoard(t, *gb)
// boardPrettyString := prettyprint.NewTFCBoardCanvas().
// Prett... |
package api
import (
"dingtalk/model"
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"github.com/jinzhu/copier"
)
// DingUser dingding user
type DingUser struct {
Tocken string `json:"tocken" yaml:"tocken"` // 应用访问tocken
BaseURL string `json:"base_url" yaml:"base_url"` // 接口地址:https://oapi.dingtalk... |
package msgs
type Handler interface {
Handle(Message) error
}
type HandlerFunc func(Message) error
func (hf HandlerFunc) Handle(msg Message) error {
return hf(msg)
}
|
/*
* SMA WebBox RPC over HTTP REST API
*
* The data loggers Sunny WebBox and Sunny WebBox with Bluetooth continuously record all the data of a PV plant. This is then averaged over a configurable interval and cached. The data can be transmitted at regular intervals to the Sunny Portal for analysis and visualization. ... |
package conf
import (
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
)
type Config struct {
Env struct {
Port int `yaml:"port"`
Dir string `yaml:"dir"`
Rabbitmq string `yaml:"rabbitmq"`
} `yaml:"env"`
}
var conf Config
func InitConfig() error {
yamlFile,err := ioutil.ReadFile("depoly... |
package ast
import (
"bytes"
"fmt"
"strings"
"github.com/axbarsan/doggo/internal/token"
)
type MapLiteral struct {
Token token.Token // The 'token.LBRACE' token.
Pairs map[Expression]Expression
}
func (ml *MapLiteral) expressionNode() {}
func (ml *MapLiteral) TokenLiteral() string {
return ml.Token.Literal
... |
package model
import (
"net/http"
"time"
)
type HttpTestCase struct {
Name string
Method string
Path string
Input []byte
Output []byte
Status int
Client http.Client
Timeout time.Duration
}
|
package user
import (
"context"
"log"
"github.com/MuhammadChandra19/go-grpc-chat/internal/errors"
"github.com/MuhammadChandra19/go-grpc-chat/internal/storage"
)
type User struct {
Username string `json:"username" db:"username"`
Name string `json:"name" db:"name"`
Email string `json:"email" db:"email"`
... |
package main
import (
"fmt"
"github.com/IngridCBarbosa/area"
)
func main() {
fmt.Println(area.Circ(6.0))
fmt.Println(area.Rect(5.0, 2.0))
// fmt.Println(area._TrianguloEq(5.0, 2.0)) => não funcionar , pois essa função é privada para outros pacotes
}
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"net"
"strings"
"time"
"github.com/hfgo/datafile"
)
type CallbackResp struct {
Msg string
Reqid int
}
func handleCallBackResp(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 32)
var resp CallbackResp
resp.Msg = "wait"
resp.Reqi... |
/*
Implement the RandomizedSet class:
RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was pr... |
package greq
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
const (
person = "person"
book = "book"
)
type Command struct {
ObjectToFetch string
}
type Person struct {
Name string
HairColor string
}
type Book struct {
Title string
CopiesSold int
... |
package testcase
type Options[T any] struct {
ch1 chan T `option:"mandatory" validate:"required"`
ch2 <-chan T `option:"mandatory"`
ch3 chan T
ch4 <-chan T
}
|
package main
import "fmt"
func main() {
var c chan int
fmt.Println("cap", cap(c), "len", len(c))
}
|
// Copyright 2014 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
package collect
import (
"opentsp.org/contrib/collect-netscaler/nitro"
"opentsp.org/internal/tsdb"
)
func init() {
registerStatFunc("responderpol... |
package fractalnoise
import (
"testing"
"github.com/lmbarros/sbxs_go_noise"
"github.com/lmbarros/sbxs_go_test/test/assert"
)
// mockedNoise is a fake noise generator, which always returns 1.0.
type mockedNoise struct{}
func (n *mockedNoise) Noise1D(x float64) float64 {
return 1.0
}
func (n *mockedNoise) Noise2... |
package testutil
import (
"fmt"
"reflect"
"runtime"
"testing"
)
const (
END = "\033[0m" // Encodes end
RED = "\033[91m"
)
// Returns a formatted string containing file name,
// line number and function name.
func getInfo() string {
pc, file, line, ok := runtime.Caller(2)
testName := ""
if ok {
... |
package main
//Embedding one type inside the other
import "fmt"
type person struct {
first, last string
age int
}
type crossfitter struct {
person
background string
}
func main() {
cf1 := crossfitter{
person: person{
first: "Brent",
last: "Fikowski",
age: 29,
},
background: "volleyba... |
//
// direct test of secure vs non-secure websockets, wss and ws uri schemes respectively
//
// to run this test:
//
// 1. "go run ws.go"
// 2. in a browser, visit unsecure url "http://localhost:8080" ---
// this is insecure version, you should see echo messages once per second
// 3. in a browser, visit secure url "htt... |
package pie_test
import (
"github.com/elliotchance/pie/v2"
"github.com/stretchr/testify/assert"
"testing"
)
func TestGroup(t *testing.T) {
assert.Equal(t, map[float64]int{}, pie.Group([]float64{}))
assert.Equal(t, map[float64]int{
1: 1,
}, pie.Group([]float64{1}))
assert.Equal(t, map[float64]int{
1: 1,
... |
package ch1
import (
"testing"
)
func Test_consumerAndProducer(t *testing.T) {
cls := make(chan struct{}, 0)
consumerAndProducer(10, cls)
close(cls)
}
|
package main
import (
"fmt"
"math/rand"
"time"
)
func testBadGoodTest() {
doWork := func(done <-chan interface{}, nums ...int) (<-chan interface{}, <-chan int) {
heartbeatStream := make(chan interface{}, 1)
intStream := make(chan int)
go func() {
defer close(heartbeatStream)
defer close(intStream)
... |
package bmrouter
import (
"encoding/json"
"fmt"
"github.com/alfredyang1986/blackmirror/bmalioss"
"github.com/alfredyang1986/blackmirror/bmcommon/bmsingleton/bmpkg"
"github.com/alfredyang1986/blackmirror/bmrouter/bmoauth"
"github.com/alfredyang1986/blackmirror/jsonapi/jsonapiobj"
"io"
"io/ioutil"
"os"
"errors... |
package main
import (
"bufio"
"middleware-bom/model"
"middleware-bom/publisher"
"middleware-bom/subscriber"
"os"
"strconv"
"strings"
"time"
)
func main() {
println("1 for measurer, 2 for measuree")
reader := bufio.NewReader(os.Stdin)
choice, _ := reader.ReadString('\n')
if strings.HasPrefix(choice, "1") ... |
package constant
type NodeType string
const (
Peer NodeType = "peer"
Orderer NodeType = "orderer"
Admin NodeType = "admin"
User NodeType = "user"
)
|
package service
import (
"fmt"
"strings"
jwt "github.com/dgrijalva/jwt-go"
"github.com/valyala/fasthttp"
)
func parseAuth(ctx *fasthttp.RequestCtx) (token, sub string, err error) {
token, sub, err = parseBearer(string(ctx.Request.Header.Peek("Authorization")))
if err != nil {
err = fmt.Errorf("cannot parse a... |
package main
import (
"fmt"
pow "github.com/bitmaelum/bitmaelum-suite/pkg/proofofwork"
"os"
"strconv"
)
func main() {
if len(os.Args) != 3 {
fmt.Printf("Usage: %s <bits> <data>", os.Args[0])
os.Exit(1)
}
bits, _ := strconv.Atoi(os.Args[1])
data := os.Args[2]
fmt.Printf("Working on %d bits proof...\n", ... |
package main
import (
"context"
"fmt"
"net/http"
"os"
"runtime"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// ServerRun server run
func ServerRun(ctx context.Context, addr string, e *gin.Engine, quitTimeout time.Duration) (err error) {
defer func() {
if err != nil {
if gin.IsDebu... |
package gates
import (
"crypto/sha256"
"encoding/hex"
"time"
)
type Opaque struct {
Id int `json:"id" db:"id"`
UserId int `json:"user_id" db:"user_id"`
Jwt string `json:"jwt" db:"jwt"`
Opaque string `json:"opaque" db:"opaque"`
CreatedAt time.Time `json:"created_at" db:"cre... |
package main
import "container/list"
//一种方法是每一次都存储下来,层序遍历完计算每层的平均值,但该方法占用空间较大
//因此考虑遍历每层的时候就进行计算,不单独进行存储
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
if root == nil {
return ... |
// Copyright 2016 Google Inc. 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 applicable... |
package main
import "fmt"
func main() {
closure()
}
func closure() {
word := "sample"
defer func(input string) {
fmt.Print("case 1: ")
fmt.Println(input)
}(word)
defer func() {
fmt.Print("case 2: ")
fmt.Println(word)
}()
word = "sample-changed"
defer func(input string) {
fmt.Print("case 3: ")
f... |
/*
Copyright © 2023 SUSE LLC
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
distri... |
package main
import "fmt"
func main() {
fmt.Println(maxSlidingWindow([]int{12, 3, 2, 4, 1}, 2))
}
func maxSlidingWindow(nums []int, k int) []int {
q := []int{}
res := make([]int, len(nums)-k+1)
for i := 0; i < len(nums); i++ {
for len(q) != 0 && nums[q[len(q)-1]] < nums[i] {
q = q[:len(q)-1]
}
q = appen... |
package main
import (
"context"
"fmt"
"log"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/crypto"
"strings"
"github.com/sanguohot/medichain/contracts/hello"
)
func main() {
client, err := ... |
// Copyright (c) 2017-2018 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package zedmanager
import (
"github.com/lf-edge/eve/pkg/pillar/types"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
)
func lookupVerifyImageConfig(ctx *zedmanagerContext,
imageID uuid.UUID) *types.VerifyImageConfig... |
package operate
import (
"strconv"
"time"
)
var (
bucketName string = "typora-pic-plat"
)
func PutObject(path string) (string, error) {
bucket, err := GetExistBucket(bucketName)
var uuid string = GenUUID()
var now time.Time = time.Now()
var remotePath = "typora/" + strconv.Itoa(now.Local().Year()) + strconv.I... |
package models
import (
"database/sql"
"fmt"
"log"
)
var conn *sql.DB
// Connect -> Connect to db
func Connect() *sql.DB {
db, err := sql.Open("mysql", "admin:admin12345@tcp(localhost:3306)/dbnotes")
if err != nil {
log.Fatal(err)
}
fmt.Println("DB Connected")
conn = db
return db
}
|
package main
import (
"fmt"
"github.com/jdxyw/skiplist-go"
)
type IntCmp struct {}
func (IntCmp) Compare(rhs, lhs interface{}) int {
rhsint := rhs.(int)
lhsint := lhs.(int)
switch result := rhsint-lhsint; {
case result == 0:
return 0
case result > 0:
return 1
default:
return -1
}
}
func (IntCmp) Nam... |
package csidh
import (
"crypto/rand"
"testing"
"github.com/cloudflare/circl/dh/csidh"
"github.com/stretchr/testify/require"
)
func TestCSIDH(t *testing.T) {
// Alice
alicePrivateKey := new(csidh.PrivateKey)
err := csidh.GeneratePrivateKey(alicePrivateKey, rand.Reader)
require.NoError(t, err)
alicePrivateK... |
/*
A function takes in two hashes as input. Both hashes contain exactly the same keys.
Return an array of keys where the values in each hash differs.
Examples
differs({a: 1, b: 2, c: 3}, {a: 3, b: 2, c: 1}) ➞ ["a", "c"]
differs({a: 1, b: 1, c: 1}, {a: 2, b: 2, c: 2}) ➞ ["a", "b", "c"]
differs({a: 3, b: 3, c: 3}, {... |
package cmd
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"gonum.org/v1/gonum/spatial/r3"
)
type OBJ struct {
V []r3.Vec
//VT []r2.Vec
//VN []r3.Vec
FS []OBJF
}
type OBJF struct {
Mtl string
F []OBJFV
}
type OBJFV struct {
V int
}
func (o *OBJ) Export(path string) error {
if !strings.HasS... |
package config
import (
"github.com/apex/log"
"github.com/caarlos0/env"
)
type Config struct {
Port string `env:"PORT" envDefault:"8081"`
AllowedOrigins []string `env:"ALLOWED_ORIGINS" envSeparator:"," envDefault:"*"`
}
func MustGet() Config {
var cfg Config
if err := env.Parse(&cfg); err != nil {
... |
package v039
import (
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// NameRecord is an address with a flag that indicates if the name is restricted
type NameRecord struct {
// The bound name
Name string `json:"name" yaml:"name"`
// The address the name resolved to.
Address sdk.AccAddress `json:"... |
// RAINBOND, Application Management Platform
// Copyright (C) 2014-2017 Goodrain Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your opt... |
package models
import (
. "asdf"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"radgo"
"strconv"
"strings"
)
//************************************************
//以下为实现radgo的logger的接口
//************************************************
type mylog struct {
log *logs.BeeLogger
}
var... |
package postgres
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/odpf/optimus/models"
"github.com/odpf/optimus/store"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type ProjectJobSpecRepository struct {
db *gorm.DB
project models.ProjectSpec
adapter *JobSpecAdapter
}
func NewProjectJobSpecRe... |
package conf
const (
DEFAULT_READ_TIMEOUT int = 5000
DEFAULT_WRITE_TIMEOUT int = 5000
DEFAULT_HANDLE_TIMEOUT int = 5000
)
// APP配置
type AppConfig struct {
Addr string `toml:"listen"` // 监听地址
ReadTimeout int `toml:"readTimeout"` // 请求读超时
HandleTimeout int ... |
package golang
import "github.com/crozz-chen/apimeta/meta"
type File struct {
Path string
Pkg string
FullPkg string
Refs []Ref
Models []meta.Model
Apis []meta.Api
}
// com.apimeta.user
type Ref struct {
Src string // @(com/apimeta/user)
Pkg string // apimeta
FullPkg string // com/apimet... |
package rp
import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
// XMLReport identifies JUnit XML format specification that Hudson supports
type XMLReport struct {
xmlSuites []xmlSuite
}
type xmlSuite struct {
XMLName string `xml:"testsuite"`
ID ... |
package roleTypeRole
import (
"google.golang.org/appengine/datastore"
)
// RoleTypeRole datastore: ",noindex" causes json naming problems !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// "Role" key is the parent key.
type RoleTypeRole struct {
RoleTypeKey *datastore.Key
}
// RoleTypeRoles is a []*RoleTypeRole
type RoleTypeRoles [... |
package main
import (
"os"
"strconv"
)
func flib(index, max, l1, l2 int) int {
if index == max {
return l2
}
return flib(index+1, max, l2, l1+l2)
}
func f(n int) int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return f(n-1) + f(n-2)
}
}
func main() {
max, _ := strconv.Atoi(os.Args[... |
package model
import (
"errors"
"fmt"
"gopkg.in/macaron.v1"
"gopkg.in/mgo.v2"
"log"
"tech/modules/setting"
"time"
//"os"
)
const (
MasterSession = "master"
MonotonicSession = "monotonic"
)
var (
singleton mongoManager
)
type (
mongoConfiguration struct {
Hosts string
Database string
Username... |
package zmq4_test
import (
zmq "github.com/pebbe/zmq4"
"errors"
"fmt"
"runtime"
"strconv"
"time"
)
var (
errerr = errors.New("error")
)
func Example_test_version() {
major, _, _ := zmq.Version()
fmt.Println("Version:", major)
// Output:
// Version: 4
}
func Example_multiple_contexts() {
chQuit := make(... |
package main
import "fmt"
//定义结构体 Emp
type Emp struct {
name string
age int8
sex byte
}
/*
结构体的一些语法糖
*/
func main() {
//使用new()内置函数实例化struct
emp1 := new(Emp)
fmt.Printf("emp1: %T , %v , %p \n", emp1, emp1, emp1)
(*emp1).name = "David"
(*emp1).age = 30
(*emp1).sex = 1
//语法糖写法
emp1.name = "David2"
emp... |
package kstcmd
import (
"../kstclient"
"../kstserver"
"fmt"
"github.com/spf13/cobra"
)
var RootCmd = &cobra.Command{
Use: "kstcmd",
Short:"simple [K:V] storage",
Long:"simple [K:V] storage",
Run: func(cmd *cobra.Command, args []string) {
cmd.Usage()
//fmt.Printf("RootCmd exec\n");
},
}
//server命令上下文
typ... |
package api
import (
"encoding/json"
"errors"
"math"
"project/app/admin/models"
"project/app/admin/models/dto"
"project/app/admin/service"
"project/common/cache"
"project/common/global"
"github.com/gin-gonic/gin"
)
const (
CtxUserIdAndName = "user"
CtxUserIDKey = "user_id"
CtxUserInfoKey = "info"
... |
package builder
import (
"fmt"
"reflect"
"sort"
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
)
func getDescStruct(opts MetricOpts, labelKeyValues map[string]string) string {
lpStrings := make([]string, 0, len(labelKeyValues))
for key, value := ran... |
/*
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
distributed under the License ... |
package main
import "fmt"
func value(number int) int {
defer fmt.Println("end")
if number > 5000 {
fmt.Println("High Value")
return number
} else {
fmt.Println("Low Value")
return number
}
}
func main() {
fmt.Println(value(6000))
fmt.Println(value(2000))
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"path/filepath"
"runtime"
"strconv"
"strings"
)
func main() {
_, file, _, _ := runtime.Caller(0)
content, err := ioutil.ReadFile(filepath.Join(filepath.Dir(file), "./input.txt"))
if err != nil {
log.Fatalln("load input error:", err)
}
rawInput := strings.Spl... |
package ws_test
import (
"net/http"
"net/http/httptest"
"net/url"
"time"
"github.com/emicklei/go-restful"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
error_types "github.com/kumahq/kuma/pkg/core/rest/errors/types"
"github.com/kumahq/kuma/pkg/core/secrets/cipher"
secret_manager "github.com/kumahq/... |
package response
import "time"
type AnimeResponse struct {
RequestHash string `json:"request_hash"`
RequestCached bool `json:"request_cached"`
RequestCacheExpiry int `json:"request_cache_expiry"`
MalID int `json:"mal_id"`
URL string ... |
// Copyright 2021 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 impl
import (
"errors"
"github.com/gorilla/websocket"
"sync"
)
type Connection struct {
wsConn *websocket.Conn
outChannel chan []byte
inChannel chan []byte
closeChannel chan []byte
mutex sync.Mutex
isClosed bool
}
func InitCreateConnection(wsConn *websocket.Conn) (conn *Connect... |
/*
Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more.
*/
package main
import (
"fmt"
"coding_bat/utils"
)
func make_ends(ints []int) []int {
if len(ints) == 0 {
return []int{}
} else if len(ints) == 1 {... |
package status
// ResponseDoc is a response declaration for documentatino pruposes
type ResponseDoc struct {
Data struct {
Attributes Response `json:"attributes"`
} `json:"data"`
}
|
package main
import (
"fmt"
)
func main() {
x := []int{11, 33, 55, 77}
y := []string{"Eleven", "Thirty three", "Fifty five", "Seventy seven"}
z := []int{22, 44, 66, 88}
fmt.Println(x)
fmt.Println(y)
fmt.Println(z)
ip := [][]int{x, z}
fmt.Println("The value of ip:", ip)
x = append(x, 99, 100)
fmt.Println(... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package armhelpers
import (
"testing"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/types"
)
func TestAzureStorageClient_CreateContainer(t *testing.T) {
cases := []struct {
name string
storag... |
package main
import (
"unsafe"
"fmt"
)
func addr_change_by_GC(){
// Go语言中对象的地址可能发生变化,因此指针不能从其它非指针类型的值生成:
// 当内存发送变化的时候,相关的指针会同步更新,但是非指针类型的uintptr不会做同步更新。
//
//同理CGO中也不能保存Go对象地址。
var x int = 42
var p uintptr = uintptr(unsafe.Pointer(&x))
//runtime.GC()
var px *int = (*int)(unsafe.Pointer(p))
fmt.Println(... |
// miscellaneous utility functions used for the landing page of the application
package cvetool
import (
"glsamaker/pkg/models"
"glsamaker/pkg/models/users"
"html/template"
"net/http"
)
// renderIndexTemplate renders all templates used for the landing page
func renderIndexTemplate(w http.ResponseWriter, user *us... |
package user_model
import "testing"
func TestParse(t *testing.T) {
ParseAuthToken("5BnE2nHyCERFJjM3158EWNnWzrzdkB1E6q8YsSyfo+7wDOMLZnDFd331p06P/mnV")
}
|
package main
import (
"fmt"
"sync"
"time"
pb "github.com/gautamrege/gochat/api"
)
/**** This is the pb.Handle struct
THIS IS FOR REFERENCE ONLY. DO NOT UNCOMMENT
type pb.Handle struct {
Name string
Host string
Port int32
}
****/
type Handle struct {
pb.Handle
Created_at time.Time
}
// Ensure that han... |
package jwallgame
import (
"fmt"
"net/http"
"bytes"
"io/ioutil"
"encoding/xml"
)
type jwAllGamesCheckerResponseEnvelope struct {
XMLName xml.Name
Body jwAllGamesCheckerResponseBody
}
type jwAllGamesCheckerResponseBody struct {
XMLName xml.Name
GetResponse jwAllGamesCheckerResponse `xml:"FN_SEL_Celeb... |
package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"testing/iotest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHTTPClientSanitizeASCIIControlCharactersC0(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(... |
package domain
import (
"errors"
"time"
)
// checkExipirationDate validates that the token is not expired.
func checkExpirationDate(exp int64) error {
now := time.Now().UTC().Unix()
if exp < now {
return errors.New("error: token is expired")
}
return nil
}
// checkWhiteList validates that the token is avalia... |
/*
* @lc app=leetcode id=39 lang=golang
*
* [39] Combination Sum
*
* https://leetcode.com/problems/combination-sum/description/
*
* algorithms
* Medium (49.04%)
* Likes: 2089
* Dislikes: 65
* Total Accepted: 354.3K
* Total Submissions: 722.4K
* Testcase Example: '[2,3,6,7]\n7'
*
* Given a set of c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.