text stringlengths 11 4.05M |
|---|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package scan implements a generic scanner. A client needs to supply
// a state machine in the form of state functions returning other state
// functions as t... |
package config
import (
"io/ioutil"
"github.com/cloudfly/ecenter/pkg/events"
"gopkg.in/yaml.v2"
)
// Config is the main configuration structure
type Config struct {
MySQL struct {
Addr string `yaml:"addr" json:"addr"`
Username string `yaml:"username" json:"username"`
Password string `... |
package main
/*
* @lc app=leetcode id=6 lang=golang
*
* [6] ZigZag Conversion
*/
func convert(s string, numRows int) string {
if numRows == 1 {
return s
}
strs := make([]string, numRows)
row, step := 0, 1
for i := 0; i < len(s); i++ {
strs[row] += string(s[i])
row += step
if row >= numRows {
row -=... |
package agent
import (
"sync"
"github.com/muka/go-bluetooth/bluez"
log "github.com/sirupsen/logrus"
"reflect"
"github.com/fatih/structs"
"github.com/muka/go-bluetooth/util"
"github.com/godbus/dbus"
)
var Agent1Interface = "org.bluez.Agent1"
// NewAgent1 create a new instance of Agent1
//
// Ar... |
package test
import (
"fmt"
"math/rand"
"testing"
"time"
"github.com/bddbnet/gospy/parser/h.bilibili.com"
)
func TestPage(t *testing.T) {
fmt.Println(h_bilibili_com.Page(30, 99)) //1
fmt.Println(h_bilibili_com.Page(30, 3)) //1
fmt.Println(h_bilibili_com.Page(30, 11)) //1
fmt.Println(time.Millisecond * tim... |
package main
import (
"os"
"io"
"fmt"
"flag"
"strings"
)
type Command struct {
Run func(cmd *Command, args []string)
Flag flag.FlagSet
Usage string
Short string
Long string
}
func (c *Command) Name() (name string) {
name = c.Usage
i := strings.Index(name, " ")
if i >= 0 {
name = name[:i]
}
return
}... |
package main
import (
"fmt"
"github.com/google/uuid"
"log"
)
func main() {
id := uuid.New()
fmt.Println(len(id))
fmt.Println(id)
fmt.Println(id.String())
id2, err := uuid.Parse(id.String())
if err != nil {
log.Fatal(err)
}
fmt.Println(len(id2))
fmt.Println(id2.String())
for i,byte := range id {
fmt.P... |
package main
import "fmt"
func main() {
k := 1
red := 0
yellow := 0
for i := 1; i <= k; i++ {
if i%2 == 0 {
temp_red := i * i
red += temp_red
} else if i%2 == 1 {
temp_yellow := i * i
yellow += temp_yellow
}
}
final := red - yellow
fmt.Println(final)
}
|
package main
import (
"log"
"io/ioutil"
"os"
"flag"
"strings"
"path/filepath"
k8sml "KubeArch/kubearch/k8sml"
ansible "KubeArch/kubearch/proletarian/ansible"
proletarian "KubeArch/kubearch/proletarian"
)
func main() {
buildArg := flag.NewFlagSet("build", flag.ExitOnError)
arch ... |
package aliases
import "time"
//Alias map user defined project names to a Common Platform Enumeration (CPE).
type Alias struct {
ID string `json:"id"`
Name string `json:"name"`
Org string `json:"org"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Vers... |
package utils
import (
"time"
"unicode/utf8"
)
func Sleep(milliseconds int64) {
time.Sleep(time.Duration(milliseconds) * time.Millisecond)
}
func FixInvalidUTF8(broken string) string {
if !utf8.ValidString(broken) {
v := make([]rune, 0, len(broken))
for i, r := range broken {
if r == utf8.RuneError {
... |
package main
import (
"fmt"
// "math/complex"
)
var (
l_size int = 0
l_start int64 = 0
// looking bool = true
)
func get_collatz_size(n int64) int {
size := 1
for ; n > 1 ; {
if n % 2 == 0 {
n=n/2
} else {
n=3*n+1
}
size+=1
}
return size;
}
func print_col... |
/**
@description:go-sidecar
@author: Angels lose their hair
@date: 2021/5/12
@version:v1
**/
package main
import (
proxy2 "go-sidecar/proxy"
"go-sidecar/servicegovernance"
)
func main(){
//service start
serviceComponent:= servicegovernance.New()
serviceComponent.Run()
//proxy start
... |
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
// ConnectedEndpoint connected_endpoint
// swagger:model ConnectedEndpoint
type ConnectedEndpoint struct {
ID uint64 `json:"id,omitempty"`
URL string `json... |
package main
import (
"fmt"
)
func main() {
x := 11
switch x {
case 1:
fmt.Println("x is 1\n")
case 2:
fmt.Println("x is 2\n")
default:
fmt.Println("default case \n")
}
switch {
case x > 10:
fmt.Println("x is bigger than 10")
case x > 100:
fmt.Println("x is very big..bigger than 100")
default:... |
// Copyright 2020 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package canvas
import (
"reflect"
"strings"
"testing"
)
func TestModifierKeys(t *testing.T) {
type modifierKeyStates struct {
altKey bool
shiftKey bo... |
package main
import "tagallery.com/api/server"
func main() {
server.StartServer()
}
|
// Copyright © 2017 Aeneas Rekkas <aeneas+oss@aeneas.io>
//
// 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 appl... |
package robot
import (
"fmt"
"github.com/ev3go/ev3dev"
)
func GetEngine() *Engine{
fmt.Println("engineFactory:: GetEngine()")
rightPorts := []string{"outC", "outD"}
leftPorts := []string{"outA", "outB"}
motorType := "lego-ev3-l-motor"
engine := new(Engine)
for _, rop := range rightPorts {
... |
package worker
import (
"context"
)
// Worker is the generic interface for a worker process store
type Worker interface {
GetWork(ctx *context.Context) error
DoWork(ctx *context.Context) error
CompleteWork(ctx *context.Context) error
}
|
package main
import (
"os"
"log"
"runtime"
"github.com/raspi/dirscanner"
"time"
"math"
"flag"
"path/filepath"
"fmt"
)
var VERSION = `0.0.0`
var BUILD = `dev`
const (
AUTHOR = `Pekka Järvinen`
YEAR = 2018
HOMEPAGE = `https://github.com/raspi/duplikaatti`
)
const (
MEBIBYTE = 1048576
GIBIBYTE = 10... |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
// lab3_1(Vinni&Beens)
package main
import (
"fmt"
"time"
)
func main() {
var n int
var h int
for n <= 0 {
fmt.Println("Enter the number of Bees: ")
fmt.Scan(&n)
}
for h <= 0 {
fmt.Println("Enter the number of Swallows: ")
fmt.Scan(&h)
}
demo(n, h)
var input string
fmt.Scan... |
package payment
import "time"
// Model is base for database struct
type Model struct {
ID uint64 `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created_at" gorm:"not null;"`
UpdatedAt time.Time `json:"updated_at" gorm:"not null;"`
DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}
// ... |
package image_test
import (
. "github.com/DennisDenuto/property-price-collector/site/image"
"context"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"io/ioutil"
"net/http"
"time"
)
var _ = Describe("SingleDownload", func() {
var server *ghttp.Server
var responseBody *... |
package main
import (
"fmt"
"net/http"
"net/url"
"github.com/gorilla/mux"
)
// Service exposes the HTTP redirection service and an API for managing the
// service and creating user interfaces.
type Service struct {
Access func(name, bind, url string)
NotFound func(w http.ResponseWriter, r *http.Request)
sit... |
package controllers
import (
"github.com/gin-gonic/gin"
"github.com/go-playground/validator"
"github.com/hunterhug/fafacms/core/config"
"github.com/hunterhug/fafacms/core/flog"
"github.com/hunterhug/fafacms/core/model"
"github.com/hunterhug/parrot/util"
"math"
"time"
)
func GetSecond2DateTimes(secord int64) s... |
// Copyright 2020 The Reed Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package blockmanager
import (
"github.com/reed/blockchain/store"
"github.com/reed/log"
"github.com/reed/types"
)
type BlockIndex struct {... |
package hw02_unpack_string //nolint:golint,stylecheck
import (
"testing"
"github.com/stretchr/testify/require"
)
type test struct {
input string
expected string
err error
}
func TestUnpack(t *testing.T) {
for _, tst := range [...]test{
{
input: "a4bc2d5e",
expected: "aaaabccddddde",
},
... |
// 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 ctxh
import (
"net/http"
log "github.com/Sirupsen/logrus"
"golang.org/x/net/context"
)
// ContextHandler defines a handler which receives a passed context.Context
// with the standard ResponseWriter and Request.
type ContextHandler interface {
ServeHTTP(context.Context, http.ResponseWriter, *http.Request... |
package main
import "fmt"
func main() {
fmt.Println("Construct Binary Search Tree from Preorder Traversal")
doTest([]int{4, 8, 12})
doTest([]int{8, 5, 1, 7, 10, 12})
doTest([]int{14, 15, 20, 22})
doTest([]int{10, 8, 5, 3})
doTest([]int{14, 10, 8, 5, 3, 15, 20, 22})
doTest([]int{14, 10, 8, 5, 3, 4, 9, 15, 20, 1... |
package route
import (
"fmt"
"net/http"
"os"
"github.com/souhub/wecircles/pkg/data"
"github.com/souhub/wecircles/pkg/logging"
)
func Circle(w http.ResponseWriter, r *http.Request) {
vals := r.URL.Query()
id := vals.Get("id")
session, err := session(w, r)
if err != nil {
logging.Info(err, logging.GetCurren... |
package controllers
import (
"database/sql"
"fmt"
"hw5_2/models"
"log"
"net/http"
"strconv"
"github.com/astaxie/beego"
"github.com/pkg/errors"
)
// MainController controller
type MainController struct {
beego.Controller
DB *sql.DB
}
// Get gets main page
func (c *MainController) Get() {
posts, err := c.g... |
package main
import (
"fmt"
"github.com/go-redis/redis"
"sync"
"time"
)
//创建客户端
//redis-cli -h 172.27.139.101 -p 25367
func initClient() (*redis.Client) {
client := redis.NewClient(&redis.Options{
Addr: "172.27.139.101:25367",
Password: "",
DB: 1,
PoolSize: 5,
})
pong, err := client.Ping().Result()//检查... |
package datastore
import (
"github.com/jinzhu/gorm"
"github.com/taniwhy/mochi-match-rest/domain/models"
"github.com/taniwhy/mochi-match-rest/domain/repository"
)
type entryHistoryDatastore struct {
db *gorm.DB
}
// NewEntryHistoryDatastore :
func NewEntryHistoryDatastore(db *gorm.DB) repository.EntryHistoryRepos... |
// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package overlay
import (
"google.golang.org/grpc"
"storj.io/storj/protos/overlay"
)
// NewServer creates a new Overlay Service Server
func NewServer() *grpc.Server {
grpcServer := grpc.NewServer()
overlay.RegisterOverlayServer(grpcS... |
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `package main
import "bytes"
func main() {
var buf bytes.Buffer
if buf.Bytes == nil && bytes.Repeat != nil && main == nil {
// ...
}
}
`
//!-input
var fset = token.NewFileSet()
func m... |
package main
func getPermutation(n int, k int) string {
fact := factorial(n)
if n == 0 {
return ""
}
list := make([]rune, n)
for i := 0; i < n; i++ {
list[i] = rune(i + 1 + '0')
}
k--
var res []rune
for n >= 1 {
fact = fact / n
num := k / fact
k = k % fact
res = append(res, list[num])
list = app... |
package cmd
import (
"context"
"errors"
"os"
"os/signal"
"syscall"
"time"
"github.com/spf13/cobra"
)
// runCmd represents the run command
var (
runCmd = &cobra.Command{
Use: "run",
Short: "Run benchmarks",
Long: "Runs benchmarks on all configured workers and store the results on disk.",
R... |
package test
import (
"testing"
"spider"
"spider/parser"
)
func TestSpider(t *testing.T) {
parser := &(parser.LocationParser{})
spider := spider.LocationSpider{}
spider.DocumentParsing("http://www.yingjiesheng.com", parser)
}
|
package mst_user
import (
"go/internal/pkg/api/app/request"
"go/internal/pkg/response"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *userHandler) CreateHandler(ctx *gin.Context) {
var req request.UserRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
response.NewErrorResponse(ctx, http.StatusBadReq... |
package turnstile
import (
"reflect"
"testing"
"time"
)
func TestExtractEvent(t *testing.T) {
tests := []struct {
name string
update Update
want *Event
}{
{
name: "private message",
update: Update{Message: &Message{From: User{ID: 1, LanguageCode: "en"}, Chat: Chat{ID: 1, Type: "private"}}},
... |
package diagnostic
import (
"context"
"github.com/logrusorgru/aurora"
"github.com/openllb/hlb/pkg/filebuffer"
)
type (
sourcesKey struct{}
colorKey struct{}
)
func WithSources(ctx context.Context, sources *filebuffer.Sources) context.Context {
return context.WithValue(ctx, sourcesKey{}, sources)
}
func Sou... |
package LatticeReduction
import (
"fmt"
"math/big"
)
// Lattice basis for int64 sized values
type Int64Basis [][]int64
func (b Int64Basis) Copy() Basis {
o := make(Int64Basis, len(b))
for i, x := range b {
o[i] = make([]int64, len(x))
for j, y := range x {
o[i][j] = y
}
}
return o
}
func (b Int64Basi... |
package main
import (
"encoding/json"
_ "encoding/json"
"fmt"
"reflect"
"strconv"
"github.com/bitly/go-simplejson"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Servers []Server
}
type ok struct {
flag string
servero Serverslice
}
func main() {
//var s = ok{... |
package flow
import (
"github.com/BaritoLog/barito-flow/prome"
"github.com/BaritoLog/go-boilerplate/errkit"
"github.com/Shopify/sarama"
cluster "github.com/bsm/sarama-cluster"
log "github.com/sirupsen/logrus"
)
const (
RetrieveMessageFailedError = errkit.Error("Retrieve message failed")
)
type ConsumerWorker ... |
package physics
import (
"engo.io/engo"
"engo.io/engo/common"
)
// ParticleComponent contains the particle-physics related properties of an entity.
// It's sufficiently described by one point in space for Newtonian Physics, except collisions which are done on bounding spheres
// It must be made legal - use NewParti... |
/*
* @lc app=leetcode.cn id=31 lang=golang
*
* [31] 下一个排列
*/
package main
import "fmt"
// @lc code=start
func nextPermutation(nums []int) {
numsLen := len(nums)
if numsLen < 2 {
return
}
i, j, k := numsLen-2, numsLen-1, numsLen-1
for i >= 0 && nums[i] >= nums[j] {
i--
j--
}
if i >= 0 {
for nums[i] ... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-18 15:25
# @File : of_剑指_Offer_26_树的子结构.go
# @Description : 判断是不是子树
# @Attention :
*/
package offer
func isSubStructure(A *TreeNode, B *TreeNode) bool {
return nil != A && B != nil && (recur(A, B) || isSubStructure(A.Left, B) || isSubStructure(A.Right, ... |
package restapi
import (
"context"
"flag"
"github.com/mirzaakhena/danarisan/infrastructure/log"
"github.com/mirzaakhena/danarisan/infrastructure/util"
"github.com/mirzaakhena/danarisan/usecase/bayarsetoran2"
"time"
)
// BayarSetoran2Handler ...
func BayarSetoranHandler2(inputPort bayarsetoran2.Inport) fun... |
package mysql
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
)
func TestGenericGetLocal(t *testing.T) {
db := getConnection()
defer db.Close()
//query := `select * from fake_account_score where id=?;`
//query := `-- select * from dev... |
package simplekvstore
import (
"reflect"
"sort"
"testing"
)
func assert(expected interface{}, actual interface{}, t *testing.T) {
if !reflect.DeepEqual(expected, actual) {
t.Errorf("\nExpected: %v"+"\n"+"Actual: %v", expected, actual)
}
}
func TestSet(t *testing.T) {
store := New()
key, val := "foo", "bar"
... |
package data
import (
"encoding/json"
"io"
)
//ToJSON utility function
func ToJSON(i interface{}, w io.Writer) error {
e := json.NewEncoder(w)
return e.Encode(i)
}
//FromJSON utility function
func FromJSON(i interface{}, r io.Reader) error {
e := json.NewDecoder(r)
return e.Decode(i)
}
|
package main
import "github.com/sirupsen/logrus"
func main() {
logrus.Info("https://github.com/golang/go/issues/30986")
}
|
package main
import (
"fmt"
"net"
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter8/grpcjson/internal"
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter8/grpcjson/keyvalue"
"google.golang.org/grpc"
)
func main() {
grpcServer := grpc.NewServer()
keyvalue.Regis... |
package main
import (
"bytes"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/mattermost/mattermost-server/v5/model"
)
type peerReportUsecase struct {
plugin *Plugin
}
const (
commandPeerReportUsage = "** Slash Command Help **\n\n /peer-report [YYYY/MM/DD]\n\n - 日付は省略可能です。\n\n - 日付を省略した場合は今週の月曜日からの集計... |
package keys
import (
"strings"
"github.com/BoutiqaatREPO/nitrous/common"
"github.com/gin-gonic/gin"
"github.com/sanksons/tavern"
"github.com/sanksons/tavern/common/entity"
)
func DeleteKeysHandler(context *gin.Context, adapter tavern.CacheAdapter) {
keysStr := context.Query("keys")
keys := strings.Split(keys... |
package domain
/*type MysqlInstallReq struct {
User string `json:"user"`
Pwd string `json:"pwd"`
Address string `json:"address"`
//Version string `json:"version"`
}*/
type AddInstanceReq struct {
Port int `json:"port" binding:"required"`
ServerId int `json:"serverId" binding:"... |
package internal
import (
"fmt"
"strings"
"github.com/ipfs/go-cid"
"github.com/multiformats/go-multibase"
"github.com/multiformats/go-multihash"
)
func multibaseB32Encode(k []byte) string {
res, err := multibase.Encode(multibase.Base32, k)
if err != nil {
// Should be unreachable
panic(err)
}
return res... |
package svr
func initSvr() bool{
return true
}
|
package config
import (
"fmt"
"testing"
)
func TestConfig(t *testing.T) {
fmt.Println(C.Debug, C.Mysql.DsnRead, C.Mysql.DsnWrite, C.Mysql)
t.Log(C.Debug)
}
|
package auth
// Spotify API Scopes
// Link: https://developer.spotify.com/documentation/general/guides/scopes
const (
ScopeAppRemoteControl = "app-remote-control"
ScopePlaylistModifyPrivate = "playlist-modify-private"
ScopePlaylistModifyPublic = "playlist-modify-public"
ScopePlaylistReadCollabora... |
/*
Command grandall is a client for grandalld.
Usage
The most common usage of grandall is to open a page in a web browser. For
example if grandalld binds "/play" to "http://play.golang.org" the destination
can be opened with a grandall command.
grandall play
If grandalld binds "/godoc" to "http://godoc.org" then ... |
package main
import (
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
)
func TestHelloWorld(t *testing.T) {
var expected = "World"
var result = hello()
if result != expected {
t.Error(
"expected", expected,
"got", result,
)
}
}
func TestGetProduto(t *testing.T) {
var expecte... |
package providers
import (
"github.com/pkg/errors"
)
var (
errInvalidCertSecret = errors.New("Invalid secret for certificate")
)
|
package rivescript_test
import (
"fmt"
"github.com/aichaos/rivescript-go"
"github.com/aichaos/rivescript-go/lang/javascript"
)
func Example() {
// Create a new RiveScript instance, which represents an individual bot
// with its own brain and memory of users.
//
// You can provide a rivescript.Config struct to... |
package kv
type SetCmd struct {
Key string
Value string
}
func (this *SetCmd) CommandName() string {
return "set"
}
// handler struct
type SetReq struct {
Key string
Value string
}
type SetResp struct {
OK bool
IsLeader bool
}
type GetReq struct {
Key string
}
type GetResp struct {
OK bool
... |
package main
import "fmt"
func foo(nums ...int) (int){
sum := 0
for _, num := range nums{
sum = sum + num
}
return sum
}
func main(){
s := make([]int, 3)
s[0] = 1
s[1] = 2
s[2] = 3
fmt.Println(foo(1,2,3,4))
fmt.Println(foo(s...))
}
|
package debugger
import (
"bytes"
"errors"
"os/exec"
"strconv"
"strings"
)
var (
ErrNotExist = errors.New("pid does not exist")
)
// find pid by command "ps aux"
func FindPidByPs(procname string) (int, error) {
cmd := exec.Command("ps", "aux")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err... |
// 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
import (
"fmt"
"io/ioutil"
"net/http"
)
func testSimpleHttp() {
fmt.Println("Begin http get")
/**
curl -X GET http://127.0.0.1:8080/check/health
{
"message": "Healthy",
"status": 200
}
*/
resp1, err1 := http.Get("http://127.0.0.1:8080/check/health")
if resp1 != nil {
defer resp1... |
/*
* Copyright 2019 Tapir Liu.
*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package skia
// ref: https://golang.org/cmd/cgo/
/*
//#cgo LDFLAGS: -L${SRCDIR}/skia/lib/shared/linux/amd64
//#cgo LDFLAGS: -Wl,-rpath,${SRCDI... |
package taillog
import (
"LogDemo/kafka"
"context"
"fmt"
"github.com/hpcloud/tail"
)
// TailTask:具体的一个日志收集的任务
type TailTask struct {
// 收集的哪一个路径下的日志
path string
// 收集的日志要放到哪个topic下面
topic string
// 具体的tailObj对象
instance *tail.Tail
// 为了能显示退出 t.run()
ctx context.Context
cancelFunc context.CancelFunc
}
//... |
package leetcode
// n & (n-1) 可以 去掉 二进制最后一个1
// 2 的n次幂的 二进制上只有 1个 1
func isPowerOfTwo(n int) bool {
return n > 0 && (n&(n-1) == 0)
}
|
package go_tests
import (
keptnmodels "github.com/keptn/go-utils/pkg/api/models"
keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0"
"github.com/keptn/keptn/shipyard-controller/models"
"github.com/stretchr/testify/require"
"net/http"
"testing"
)
func Test_UniformRegistration(t *testing.T) {
uniformIntegration ... |
package server
type pathContext struct {
download bool
sort *string // keep different for param is not specified or is empty
defaultSort string
}
func (ctx *pathContext) QueryString() string {
// ?download&sort=x/
buffer := make([]byte, 1, 18)
buffer[0] = '?'
if ctx.download {
buffer = append(buff... |
package forum
import (
"time"
"github.com/gin-gonic/gin"
"github.com/go-pg/pg"
)
func (p *Plugin) indexTags(l string, c *gin.Context) (interface{}, error) {
var items []Tag
err := p.DB.Model(&items).Column("id", "name").
Order("updated_at DESC").Select()
return items, err
}
func (p *Plugin) showTag(l string... |
package valexa
import (
"testing"
)
func Test_EchoResponse_SetShouldEndSession(testingT *testing.T){
er := &EchoResponse{}
er.SetEndSession(true)
if !er.Response.ShouldEndSession {
testingT.Fatal("err")
}
}
func Test_EchoResponse_OutputSpeech(testingT *testing.T){
er := &EchoResponse{}
er.OutputSpeech("123... |
package utils
import "github.com/Sirupsen/logrus"
type SimpleLogrusHook struct {
OnFire func(*logrus.Entry)
}
func (this *SimpleLogrusHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}... |
package main
import (
"fmt"
"strings"
)
func main() {
//use the strings method to find the last occ of @
address := "\" \"@xample.org"
finalStr := ""
index := strings.LastIndex(address, "@")
index++
for i := index; i < len(address); i++ {
finalStr += string(address[i])
}
fmt.Println(finalStr)
}
|
package main
import (
"github.com/davecgh/go-spew/spew"
"strconv"
"strings"
)
func subdomainVisits(ss []string) []string {
m := map[string]int{}
for _, v := range ss {
vs := strings.Split(v, " ")
count, _ := strconv.Atoi(vs[0])
m[vs[1]] += count
for i, ch := range v... |
package render
import (
"fmt"
"math"
"github.com/grahamjenson/asteroids/game"
"github.com/grahamjenson/asteroids/js/canvas"
"github.com/grahamjenson/asteroids/vector2d"
)
func RenderGame(ctx *canvas.Context2D, g *game.Game, human bool) {
switch g.State {
case "menu":
RenderMenu(ctx, g)
RenderAlways(ctx, g... |
package main
import (
"html/template"
"net/http"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseFiles("templates/tpl.gohtml"))
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// to change the message printed on the site, replace the text below... |
package main
import (
"fmt"
"reflect"
"encoding/json"
"log"
)
func main() {
//TypeOf()
//TypeValue()
//Set()
//refOpStruct()
//refChangeStruct()
//sliceAppend()
jsonRef()
}
func TypeOf() {
var a = 10
var i interface{}
i = a
t := reflect.TypeOf(i)
switch t.Kind().String() { //Kind是基础类型 结构体会输出struct, n... |
package driver
import (
vmnet "github.com/vlorc/lua-vm/net"
"net/url"
)
type Factory func(uri *url.URL, parent, factory vmnet.NetDriver) (vmnet.NetDriver, error)
|
/*main is the entry point package for this application.
*
*/
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/rs/cors"
)
// port and portFlag handle the port for this application. The default is
// arbitrarily set to 8080.
var port int
var ... |
package config
import (
"fmt"
"os"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"github.com/srl-labs/containerlab/nodes"
"github.com/srl-labs/containerlab/types"
"inet.af/netaddr"
)
const (
systemIP = "systemip"
)
type Dict map[string]interface{}
// Prepare variables for all nodes. This will also ... |
package article
import (
"encoding/json"
"github.com/go-chi/render"
"github.com/google/uuid"
"github.com/hardstylez72/bblog/internal/api/controller"
ma "github.com/hardstylez72/bblog/internal/api/model/article"
"github.com/hardstylez72/bblog/internal/storage/article"
"net/http"
)
func (c articleController) Sav... |
package main
import (
"fmt"
)
// 找出数组中出现超过一半的数
func majorityElement(nums []int) int {
key := nums[0]
count := 1
for k, v := range nums {
if k == 0 {
continue
}
if key == v {
count++
} else {
count--
}
if count == 0 {
key = v
count = 1
}
}
fmt.Println(count)
return key
}
func m... |
/*
* @lc app=leetcode.cn id=112 lang=golang
*
* [112] 路径总和
*/
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNod... |
package a
import (
"math/rand"
)
func Presentation() ([]int, int) {
s := rand.Intn(900)
max := 100000
data := make([]int, max)
for i := 0; i < max; i++ {
data[i] = i
}
return data, s
}
func LSearch(data []int, s int) int {
for i, v := range data {
if v == s {
return i
}
}
return -1
}
func B... |
package cli
import (
"bytes"
"errors"
"io/ioutil"
"os"
"testing"
"github.com/koinos/koinos-cli/internal/cliutil"
util "github.com/koinos/koinos-util-golang"
"github.com/shopspring/decimal"
"github.com/stretchr/testify/assert"
)
func TestSatoshiToDecimal(t *testing.T) {
v, err := util.SatoshiToDecimal(10000... |
package sv
import (
"reflect"
"testing"
)
var ccfg = CommitMessageConfig{
Types: []string{"feat", "fix"},
Scope: CommitMessageScopeConfig{},
Footer: map[string]CommitMessageFooterConfig{
"issue": {Key: "jira", KeySynonyms: []string{"Jira"}},
"refs": {Key: "Refs", UseHash: true},
},
Issue: CommitMessageIss... |
package cli
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/gov/client/cli"
gov "github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/cosmos-sdk/x/upgrade/types"
"github.com/gookit/gcli/v3"
"github.com/ovrclk/akcmd/client"
)
const (
FlagUpgradeHeight = "upgrade-height"... |
package common
import (
"fmt"
"net/http"
"github.com/GoAdminGroup/go-admin/modules/config"
"github.com/gavv/httpexpect"
)
func normalTest(e *httpexpect.Expect, sesID *http.Cookie) {
fmt.Println()
printlnWithColor("Normal Table", "blue")
fmt.Println("============================")
// show
printlnWithColor... |
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"os"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
"github.com/ghodss/yaml"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/ku... |
// httpheader
package common
const(
HeaderDate = "Date"
HeaderContentType = "Content-Type"
HeaderContentMd5 = "Content-Md5"
HeaderOssPrefix = "X-Oss"
HeaderOssACL = "X-Oss-Acl"
)
|
package cache
import (
"github.com/garyburd/redigo/redis"
"time"
)
const (
defaultMaxIdle = 5
defaultMaxActive = 20
defaultIdleTimeout = time.Minute * 5
)
// Rediscache - объект для работы с redis
type Rediscache struct {
pool *redis.Pool
}
// NewRediscache - конструктор Rediscache
func NewRediscache(ad... |
package logger
import (
"log"
"os"
"strings"
)
//INFO -- To print the info logs
func INFO(message ...string) {
info := log.New(os.Stdout,
"INFO: ",
log.Ldate|log.Ltime)
info.Println(strings.Join(message, ""))
}
//ERROR -- To print the error logs
func ERROR(message ...string) {
error := log.New(os.Stdout,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.