text stringlengths 11 4.05M |
|---|
package main
import log "github.com/junwangustc/ustclog"
type Service interface {
Open() error
Close() error
}
type Server struct {
services []Service
cfg *Config
}
func (s *Server) Open() error {
if err := func() error {
for _, service := range s.services {
log.Println("start Opening service %T", ser... |
package color
import "math"
func Lighten(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.L += v
hsl.L = clamp(hsl.L)
return hsl.RGB()
}
func Darken(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.L -= v
hsl.L = clamp(hsl.L)
return hsl.RGB()
}
func Saturate(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.S += v
hs... |
package shooting
type Component struct {
Cooldown uint
// ticks to armed
tta uint
BulletForce float64
BulletDamage float64
BulletLifetime uint
}
func (c Component) Armed() bool {
return c.tta == 0
}
type Controls struct {
Shooting bool
}
type Controller chan Controls
|
package generic
import "github.com/iotaledger/hive.go/objectstorage"
type StorableObjectFlags = objectstorage.StorableObjectFlags
|
package main
import (
"os"
"fmt"
"log"
"net"
"time"
"os/signal"
"io/ioutil"
"hash/crc32"
"encoding/binary"
)
func asyncAccept(listener *net.UnixListener) <-chan *net.UnixConn {
ch := make(chan *net.UnixConn)
go func() {
for {
conn, err := listener.AcceptUnix()
if err != nil {
log.Print(err)
... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package filemanager
import (
"context"
"fmt"
"math/rand"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome... |
package id3
import (
"encoding/binary"
"reflect"
"testing"
)
func TestParseID3TagSize(t *testing.T) {
result := parseID3TagSize([]byte{0, 0, 2, 1})
if result != 257 {
t.Fatalf("failed test")
}
}
func TestSizeFromUintToByte(t *testing.T) {
cases := []struct {
in size_t
expected []byte
}{
{in: 25... |
package util
type Queue interface {
Push(interface{})
Pop() interface{}
Peek() interface{}
Size() int
IsEmpty() bool
}
func NewQueue() *queueImpl {
return &queueImpl{
nil,
nil,
0,
}
}
//Single linked list node
type SNode struct {
Val interface{}
Next *SNode
}
// Not thread safe
type queueImpl struct... |
// SPDX-FileCopyrightText: Copyright 2021 The Go Language Server Authors
// SPDX-License-Identifier: BSD-3-Clause
package jsonrpc2
import (
"fmt"
"github.com/segmentio/encoding/json"
)
// Version represents a JSON-RPC version.
const Version = "2.0"
// version is a special 0 sized struct that encodes as the jsonr... |
package dcrlibwallet
import (
"github.com/asdine/storm"
)
const (
userConfigBucketName = "user_config"
LogLevelConfigKey = "log_level"
SpendUnconfirmedConfigKey = "spend_unconfirmed"
CurrencyConversionConfigKey = "currency_conversion_option"
IsStartupSecuritySetConfigKey = "startup_security_set"
StartupSe... |
package divisible_test
import (
"testing"
"github.com/ifreddyrondon/go-workshop/santiago-nov2018/resources/src/13_testing/divisible"
)
func TestSum(t *testing.T) {
tt := []struct {
name string
top int
by []int
expect int
}{
{
name: "when top 0 expected 0",
top: 0,
by: []int{3... |
package animatedArr
import (
"math"
"time"
)
func (a *AnimArr) generateShellSortGaps() []int { // Generate A083318 gaps O(n^(3/2))
var out = []int{1} // Init with 1
for i, k := 0, 1; k < len(a.Data); i, k = i + 1, int(math.Ceil(math.Pow(2, float64(i)) + 1)) {
println(k, "k")
out = append(out, k)
}
retur... |
// Copyright (c) 2014-2018 Salsita Software
// Use of this source code is governed by the MIT License.
// The license can be found in the LICENSE file.
package pivotal
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/url"
)
const (
// LibraryVersion is used to give the UserAgent some additional contex... |
package scraper
import (
"fmt"
"math"
"sync"
"time"
"github.com/sirupsen/logrus"
)
type Progress struct {
m sync.Mutex
count int
limit int
}
const CHUNK_SIZE int = 50
func (s Scraper) Start() {
progress := Progress{count: 0, limit: s.Args.Limit * len(s.Args.Years) * len(s.Args.Prefixes)}
for _, prefi... |
package usecase
import (
"errors"
"marketplace/transactions/domain"
"marketplace/transactions/internal/infrastructure/accounts"
"marketplace/transactions/internal/infrastructure/ads"
"marketplace/transactions/internal/request"
"strings"
"github.com/gin-gonic/gin"
"github.com/go-pg/pg/v10"
"github.com/sirupse... |
package main
import (
"flag"
"fmt"
"net"
"github.com/2beens/network-programming-with-go/my_tests/desktop_laptop_connection"
"github.com/eiannone/keyboard"
"github.com/kataras/golog"
)
func main() {
golog.SetLevel("debug")
listenAddr := flag.String("addr", "", "listen address, e.g. 192.168.178.1")
listenPor... |
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package platform
import (
"context"
"fmt"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"unicode"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/rialto... |
package common
import (
"debug/elf"
"encoding/json"
"io/ioutil"
)
type KernelMeta struct {
Machine string `json:"machine" yaml:"machine"`
Platform string `json:"platform" yaml:"platform"`
Version string `json:"version" yaml:"version"`
From string `json:"from" yaml:"from"`
}
func LoadKernelMeta(path stri... |
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// DatatypeShort Core Datatype for numeric value.
// A signed 16-bit integer with a minimum value of -32,768 and a maximum value of... |
//go:build !darwin && !windows
// +build !darwin,!windows
package idle
// NewIdleGetter returns a new idle getter for windows
func NewIdleGetter() (Getter, error) {
return nil, &unsupportedError{}
}
|
package controllers
import (
"fmt"
"html/template"
"net/http"
"models"
"session"
)
// Index is top page action shows top page
func Index(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
fmt.Println(err)
}
token := session.Start(w, r)
tm... |
package routes
import (
"commerce/auth"
"commerce/context"
"commerce/helpers"
"commerce/models"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func newMiddlewares(
models *models.Models,
jwt auth.Auth,
) *middlewares {
return &middlewares{
models: models,
jwt: jwt,
}
}
// Users router
type midd... |
package etherscan
import (
"github.com/gin-gonic/gin"
"github.com/trustwallet/blockatlas/coin"
"github.com/trustwallet/blockatlas/pkg/blockatlas"
)
type Platform struct {
CoinIndex uint
RpcURL string
client Client
}
func Init(coin uint, api, rpc string) *Platform {
return &Platform{
CoinIndex: coin,
... |
package main
import (
"finance/api/account"
"finance/api/business"
"finance/api/common"
_ "finance/models"
_ "finance/models/init"
"finance/plugins"
"finance/plugins/jwt_auth"
"github.com/gin-gonic/gin"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
if plugins.Conf... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
var logger *log.Logger
func init() {
logger = log.New()
logger.SetLevel(log.DebugLevel)
log.SetOutput(os.Stdout)
logger.SetFormatter... |
package main
import (
"fmt"
"math/rand"
"runtime"
"time"
)
func main() {
//print()
//award()
getNum()
}
func print() {
runtime.GOMAXPROCS(runtime.NumCPU())
chan_n := make(chan bool)
chan_c := make(chan bool, 1)
done := make(chan struct{})
go func() {
for i := 1; i < 11; i += 2 {
<-chan_c
fmt.Prin... |
/*
Copyright 2019 Blood Orange
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 MySQL
import (
"AlgorithmPractice/src/common/Intergration/DB"
_ "github.com/go-sql-driver/mysql" // go grammar:在使用的地方需要隐式用到,不写会报错:err:sql: unknown driver "mysql" (forgotten import?)
"testing"
)
func TestNewDBMysqlCluster(t *testing.T) {
db := GetDBMysqlCluster()
df, _ := db.ExecQuery("DigitalTrans")
for... |
/*
Copyright 2021 The Skaffold 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... |
package knowledge
import "testing"
func TestRegion(t *testing.T) {
const (
operationUnit PartyType = PartyType(1)
region PartyType = PartyType(2)
division PartyType = PartyType(3)
salesOffice PartyType = PartyType(4)
)
// commissionerになれるPartyType
commissioners := PartyTypes{operationUnit, r... |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func shortestRep(q string) int {
r := 1
for i := 1; i < len(q); i++ {
if q[i] != q[i-r] {
r = i + 1
}
}
return r
}
func main() {
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data... |
package to_test
import (
"testing"
"time"
"github.com/shandysiswandi/echo-service/pkg/to"
"github.com/stretchr/testify/assert"
)
func TestCurrentTimezone(t *testing.T) {
utc := time.Now().UTC()
act := to.CurrentTimezone("Asia/Jakarta", utc)
assert.NotEqual(t, utc, act)
act = to.CurrentTimezone("Asi/Jakarta",... |
package arbitration
import "github.com/go-trading/lightning/core"
func (b *Bot) onStatusChange(symbol *core.Symbol, status core.SymbolStatus) {
log.Errorf("TODO new status for %v is %v", symbol.Name(), status)
return
}
|
package converter
import (
"github.com/koki/short/converter/converters"
"github.com/koki/short/types"
serrors "github.com/koki/structurederrors"
admissionregv1alpha1 "k8s.io/api/admissionregistration/v1alpha1"
admissionregv1beta1 "k8s.io/api/admissionregistration/v1beta1"
apps "k8s.io/api/apps/v1"
appsv1beta1 ... |
package hosts
import (
"github.com/jrapoport/gothic/core"
"github.com/jrapoport/gothic/hosts/rpc"
"github.com/jrapoport/gothic/hosts/rpc/account"
"github.com/jrapoport/gothic/hosts/rpc/health"
"github.com/jrapoport/gothic/hosts/rpc/user"
)
const rpcWebName = "rpc-web"
// NewRPCWebHost creates a new rpc host.
fu... |
package main
import (
"errors"
"fmt"
"os"
)
func main() {
f, err := os.Open("file.txt")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(f)
}
// Custom errors
myError := errors.New("new error")
fmt.Println(myError)
attendance := map[string]bool{
"AAA": true,
"BBB": true}
attended, ok := at... |
package main
import (
"fmt"
balancer "github.com/fufuok/load-balancer"
)
func main() {
var choices []*balancer.Choice
// for RoundRobin/Random/ConsistentHash
nodes := []string{"A", "B", "C"}
choices = balancer.NewChoicesSlice(nodes)
// or
// choices = []*balancer.Choice{
// {Item: "A"},
// {Item: "B"},... |
package dbs
import (
"fmt"
"log"
"strconv"
"database/sql"
_ "github.com/lib/pq"
)
type Machine struct {
Id string
Nam string
Cpu string
Mem int
}
func dbConnectTest() (string){
return "user=postgres password=1111 dbname=postgres sslmode=disable"
}
func d... |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
type FlagData struct {
Username string
Flag string
Readonly bool
}
var globalDB *sql.DB
const sqliteTest = "/tmp/flagsrv.db3"
const mysqlEnv = "MYSQL_DB"
type LoginResult int
con... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package k8s
import (
"context"
"encoding/json"
"time"
"github.com/pkg/errors"
monitoringV1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
mmv1alpha1 "github.com/matte... |
package web
import (
"text/template"
)
type Document struct {
Close bool //关闭文档
GenerateHtml bool //生成Html
Static string
Theme string
Attr map[string]string
Css map[string]string
Js map[string]string
Img m... |
package main
type ListNode struct {
Val int
Next *ListNode
}
///////////////////// 使用转换成切片的方式 ///////////////////////////////
func isPalindrome(head *ListNode) bool {
vallist := []int{}
for head != nil {
//把链表转换成切片
vallist = append(vallist, head.Val)
head = head.Next
}
n := len(vallist)
//使用双指针法判断是否为回文
... |
package control
import (
"fmt"
_ "github.com/et-zone/embi/dao"
"github.com/et-zone/embi/model"
"github.com/gin-gonic/gin"
)
func TPost(c *gin.Context) {
t := &model.ETarget{}
err := c.Bind(t)
if err != nil {
fmt.Println(err.Error())
c.JSON(200, gin.H{
"message": "ok",
})
return
}
// err = dao.In... |
package requests
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
)
// SelectMasteryPath Select a mastery path when module item includes several possible paths.
// Requires Mastery Paths feature to be enabled. Returns a compound doc... |
package main
import (
"github.com/sadasant/scripts/go/euler/euler"
"sort"
"strings"
)
func solution(file string) (total int) {
lines := strings.Split(file, ",")
sort.Strings(lines)
lower_limit := 64
for k, v := range lines {
worth := 0
// euler.Printf("%v %v ", k, v)
for _, _v := range v {
i_v := int(... |
package main
import (
"net"
"net/http"
"strings"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func RemoteAddress(c echo.Context) string {
AddressAndPort := strings.Split(c.Request().RemoteAddr, ":")
Address := AddressAndPort[0]
return Address
}
func ShowIP(c echo.Context) error {
Addr... |
package models
import(
"errors"
"github.com/tawfeeq0/auth_server/security"
)
type SdbUser struct{
Name string `json:"Description"`
BadgeNo string `json:"Name"`
Categories []string `json:"CategoryNames"`
}
func (user SdbUser) SignToken() (string, error) {
if user.BadgeNo != "" && len(user.Categories) >0 {
ret... |
package main
import (
"os"
"strings"
"github.com/jinzhu/configor"
)
type Config struct {
Server struct {
Address string `toml:"address" required:"true"`
Username string `toml:"username" required:"true"`
Password string `toml:"password" required:"true"`
} `toml:"server"`
Session struct {
Path string `t... |
package main
import (
"fmt"
"time"
"cards"
"engine"
"engine/graphics"
)
func main() {
graphics := graphics.InitCanvasGraphics()
fmt.Println("Loading image...")
image := graphics.LoadImage("cards.png")
go (func() {
for !image.Loaded() {
time.Sleep(50)
}
fmt.Println("Images loaded.")
draw(grap... |
package gotun2socks
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/elazarl/goproxy"
"github.com/inconshreveable/go-vhost"
)
//import _ "net/http/pprof"
var (
proxy *goproxy.ProxyHttpServer
server *http.Server
)
func i... |
package main
import (
"net/http"
"fmt"
"github.com/jfyne/live"
)
var cookieStore = live.NewCookieStore("lamevaaplicacio", []byte("elmeusecret"))
func main(){
logoutHandler := NewLogoutHandler()
loginHandler := NewLoginHandler()
infoHandler := miInformacion()
http.Handle("/info", infoHandler)
http.Ha... |
package backend
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/zlangbert/hrp/config"
"mime/multipart"
)
// A Backend is a generic interface for chart storage
type Backend interface {
Initialize() error
GetIndex() ([]byte, error)
GetChart(string) ([]byte, error)
PutChart(filename string,... |
// Copyright 2018 The gVisor 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 agree... |
package iface
type IMsgHanler interface {
AddRouter(uint32,IRouter)
DoMsgRouter(IRequest)
}
|
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package dynamiclistener
func OnlyAllow(str string) func(...string) []string {
return func(s2 ...string) []string {
for _, s := range s2 {
if s == str {
return []string{s}
}
}
return nil
}
}
|
package main
import(
"math/rand"
//"time"
"fmt"
"./gamelogic"
"bufio"
"os"
"log"
)
func main(){
gamelogic.Rand_init()
//reader := bufio.NewReader(os.Stdin)
fmt.Printf("Welcome to Five Card Draw! (press 'enter' between messages to continue)")
bufio.NewReader(os.Stdin).ReadBytes('... |
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package kernel
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"chromiumos/tast/common/testexec"
"chromiumos/tast/testing"
)
func... |
package main
import (
"flag"
"math/rand"
"github.com/lovung/sortBigFile/lib/golib"
)
func main() {
fo := flag.String("o", "resources/list.txt", "file path to write to")
num := flag.Int("n", 1000000, "number of items")
flag.Parse()
slice := rand.Perm(*num)
golib.WriteFile(*fo, slice, len(slice))
}
|
package tempconv
import (
"math"
"testing"
)
// TestKToC tests KToC
func TestKToC(t *testing.T) {
// Test the conversion from Kelvin to Celsius
k := Kelvin(0)
c := KToC(k)
if c != -273.15 {
t.Errorf("KToC(273.15) failed: %v\n", c)
}
}
// TestKToF tests KToF
func TestKToF(t *testing.T) {
// Test the convers... |
package hangouts
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/seibert-media/golibs/log"
"go.uber.org/zap"
googleAuth "golang.org/x/oauth2/google"
)
// Hangouts handler
type Hangouts struct {
*http.Client
URL string
}
// New Hangouts client
func New(ctx context.Conte... |
package main
type foo struct {
bar int
}
func main() {
var f foo
// := 操作符不能用于结构体字段赋值。
f.bar, tmp := 1, 2
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/syucream/numeronymize/src/numeronymize"
)
func main() {
in, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
numeronymized := numeronymize.Numeronymize(string(in))
fmt.Println(numeronymized)
}
|
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
import (
"fmt"
"net/http"
"github.com/mainflux/mainflux/pkg/errors"
)
func createError(e error, statusCode int) error {
httpStatus := fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode))
return errors.Wrap(e, errors.New(... |
package backend
import (
"net/http"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
"github.com/MiCHiLU/goapp-scaffold/app"
)
func init() {
service := goa.New("appengine")
service.Use(middleware.RequestID())
service.Use(middleware.LogRequest(true))
service.Use(middleware.ErrorHandler(servic... |
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
strfmt "github.com/go-openapi/strfmt"
... |
package leetcode
func minArray(numbers []int) int {
if len(numbers) == 0 {
return 0
}
begin := 0
end := len(numbers) - 1
mid := 0
for begin < end {
mid = (begin + end) / 2
if numbers[mid] < numbers[end] {
end = mid
} else if numbers[mid] > numbers[end] {
begin = mid + 1
} else {
end--
}
}
... |
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
)
var confirm bool
// nukeCmd represents the nuke command
var nukeCmd = &cobra.Command{
Use: "nuke",
Short: "Nuke the database",
Long: `Deletes the database directory.`,
Run: func(cmd *cobra.Comman... |
package web
import (
"encoding/json"
"github.com/RemmargorP/memjudge/api"
"net/http"
)
func (wi *WebInstance) APISignUpHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
decoder := json.NewDecoder(r.Body)
var signupdata struct {
Login string... |
package prometheus
import (
"context"
"encoding/json"
"fmt"
"strings"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// returns the prometheus service name
func GetPrometheusService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
services, ... |
package main
import (
"log"
"fmt"
"time"
"io/ioutil"
"net/http"
"strconv"
"encoding/json"
"github.com/gorilla/mux"
)
func checkTerminalVersion(version string) bool {
const LAST_CLIENT_VERSION = "2.3.1"
if version == LAST_CLIENT_VERSION {
return true
}
return false
}
func extractUint64(va... |
/*
* Copyright 2019, Offchain 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 ag... |
package conv
import (
"errors"
"image/jpeg"
"image/png"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
const (
contentTypeJPEG = "image/jpeg"
contentTypePNG = "image/png"
contentTypeOther = "application/octet-stream"
extensionJPEG = ".jpg"
extensionPNG = ".png"
)
// Indecates file destinatio... |
// Copyright 2021 - 2021 The goword Authors. All rights reserved. Use of
// this source code is governed by a MIT license that can be found in
// the LICENSE file.
//
// Package goword providing a set of functions that allow you to write to
// and read from DOCX files. Supports reading and writing
// wordprocessing doc... |
// Copyright (c) 2017 Kuguar <licenses@kuguar.io> Author: Adrian P.K. <apk@kuguar.io>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
//... |
// https://www.hackerrank.com/challenges/30-recursion
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func main() {
n := answer(os.Stdin)
fmt.Println(n)
}
func answer(input io.Reader) int {
in := bufio.NewReader(input)
line, err := in.ReadString('\n')
if err != nil {
if err != io.EO... |
package cpu
import (
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/libbeat/common"
)
func init() {
if err := mb.Registry.AddMetricSet("use", "cpu", New); err != nil {
panic(err)
}
}
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
return &CPUMetricSet{
BaseMetricSet: base,
},nil... |
package main
import (
// "net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/YanshuoH/douban-reading-stat/db"
"github.com/YanshuoH/douban-reading-stat/controllers"
"github.com/YanshuoH/douban-reading-stat/middlewares"
)
const (
// Port at which the server starts listening
Port = "3000"
)
func init... |
// +build tools
package tools
// go install github.com/golangci/golangci-lint/cmd/golangci-lint github.com/MarioCarrion/nit/cmd/nit
import (
_ "github.com/MarioCarrion/nit/cmd/nit"
_ "github.com/golangci/golangci-lint/cmd/golangci-lint"
)
|
package Contains_Duplicate_II
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestOK(t *testing.T) {
ast := assert.New(t)
ast.Equal(containsNearbyDuplicate([]int{1, 2, 3, 4, 5, 1}, 3), false)
ast.Equal(containsNearbyDuplicate([]int{1, 2, 3, 1}, 3), true)
ast.Equal(containsNearbyDuplicate([]int{1... |
package entity
type ClientModifyRequestParam struct {
AccessToken string `json:"access_token"`
Tags []string `json:"tags"`
// TODO配列にする
ItemIDs string `json:"item_ids"`
}
type ModifyRequestParam struct {
ConsumerKey string `json:"consumer_key"`
AccessToken string `json:"access_token"`... |
package dbschedules
// Recoverable checks if a schedule is recoverable.
// The schedule should not contain any Abort actions.
func Recoverable(s Schedule) bool {
lastWrite := map[string]string{}
committed := map[string]bool{"": true}
deps := map[string]map[string]bool{}
for _, t := range s.Transactions() {
deps[... |
package raws // import "github.com/BenLubar/dfide/raws"
import (
"reflect"
"strconv"
"strings"
"sync"
)
type stringOrIndex struct {
String string
Index int
}
func makeIndexString(s string) []stringOrIndex {
parts := strings.Split(s, ".")
converted := make([]stringOrIndex, len(parts))
for i, p := range part... |
package crawler
import (
"context"
"fmt"
log "git.ronaksoftware.com/blip/server/internal/logger"
"git.ronaksoftware.com/blip/server/internal/pools"
"git.ronaksoftware.com/blip/server/internal/tools"
"git.ronaksoftware.com/blip/server/pkg/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/b... |
// Copyright 2020 Liquidata, 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... |
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
timeout := make(chan int, 1)
go func() {
// time.Sleep(time.Second)
timeout <- 1
}()
go func() {
// time.Sleep(time.Second)
ch <- 30
}()
time.Sleep(time.Second)
// 监听channel上数据流动, ch,timeout 谁先来,随机选择执行
select {
cas... |
package basic
import "fmt"
func VariableGo() {
fmt.Println("hello world")
/*
VALUES
*/
fmt.Println("go" + "lang")
fmt.Println("Penjumlahan 1+1 = ", 1+1)
fmt.Println("Float 7.0/3.0 = ", 7.0/3.0)
fmt.Println(true && false)
/*
Variables
- bisa diclare 1 atau lebih variable sekaligus
- go langsung bs ta... |
package handlers
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/config"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/services"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/models"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/logs"
)
var (
errSecretMismatch = er... |
package main
import (
"net"
)
type XClient struct {
UserID int64
client *net.Conn
}
func (c *XClient) Login() {
}
func (c *XClient) Ping() {
}
|
package models
import (
"github.com/mobilemindtec/go-utils/beego/db"
)
type Cidade struct {
Id int64 `form:"-" json:",string,omitempty"`
Nome string `orm:"size(100)" valid:"Required;MaxSize(100)" form:""`
Estado *Estado `orm:"rel(fk);on_delete(do_nothing)" valid:"Required;" form:""`
Session *db.Sessio... |
package optioner_test
import (
"testing"
"github.com/boundedinfinity/go-optioner"
"github.com/stretchr/testify/assert"
)
func Test_Some_with_string(t *testing.T) {
actual := optioner.Some("s")
assert.Equal(t, actual.Empty(), false)
assert.Equal(t, actual.Defined(), true)
assert.Equal(t, actual.Get(), "s")
a... |
package main
import (
"log"
"os"
"text/template"
"time"
"tourOfGolang/ch4/github"
)
// !+template
const templ = `
{{.TotalCount}} issues:
{{range .Items}}--------------------
Number:{{.Number}}
User: {{.User.Login}}
Title: {{.Title | printf "%.64s"}}
Age: {{.CreatedAt | daysAgo}} hours ago
{{end}}
`
// !-tem... |
package factory
import (
"fmt"
"github.com/mitchellh/cli"
"seeder/constants"
)
func Version() (cli.Command, error) {
version := &versionCommandCLI{}
return version, nil
}
type versionCommandCLI struct {
Args []string
}
func (c *versionCommandCLI) Run(args []string) int {
c.Args = args
fmt.Println(constants.... |
package cli
import (
"fmt"
"index/suffixarray"
"io"
"regexp"
"sort"
"strings"
"github.com/andreyvit/diff"
"github.com/fatih/color"
)
// SearchingCommand interface to describe a command that performs a search operation
type SearchingCommand interface {
GetSearchParams() SearchParameters
}
// SearchParameter... |
package requests
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
"github.com/atomicjolt/canvasapi/models"
)
// ListQuestionsInQuizOrSubmission Returns the paginated list of QuizQuestions in this quiz.
// ht... |
package main
import (
"bytes"
"crypto/tls"
"encoding/binary"
"fmt"
)
func main() {
data := []byte("[这里才是一个完整的数据包]")
l := len(data)
fmt.Println(l)
magicNum := make([]byte, 4)
binary.BigEndian.PutUint32(magicNum, 0x123456)
lenNum := make([]byte, 2)
binary.BigEndian.PutUint16(lenNum, uint16(l))
packetBuf := ... |
package stringUtil
import (
"testing"
)
func TestIsNum(t *testing.T) {
t.Log(IsNum("sfd"))
t.Log(IsNum("123"))
t.Log(IsNum("123.3"))
}
func TestSplit(t *testing.T) {
for _,s:=range Split("sfd,,ff,ffs",","){
t.Log(s)
}
}
|
package search
import "math"
func BinarySortExist(arr []int, v int) bool {
if arr == nil || len(arr) == 0 {
return false
}
if len(arr) == 1 {
if arr[0] == v {
return true
} else {
return false
}
}
L := 0
R := len(arr) - 1
for L < R {
mid := L + (R-L)/2
if arr[mid] == v {
return true
}... |
package main
/*
Given an array A of 0s and 1s, divide the array into 3 non-empty parts such that all of these parts represent the same binary value.
If it is possible, return any [i, j] with i+1 < j, such that:
A[0], A[1], ..., A[i] is the first part;
A[i+1], A[i+2], ..., A[j-1] is the second part, and
A[j], A[j+1], ... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package wiredhostapd contains utilities for establishing a hostapd server for use with 'driver=wired'
// (i.e., Ethernet or similar).
package wiredhostapd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.