text stringlengths 11 4.05M |
|---|
package services
import (
"KServer/library/kiface/isocket"
"KServer/manage"
"KServer/proto"
"KServer/server/utils/msg"
"fmt"
)
type SocketDiscovery struct {
IManage manage.IManage
}
func NewSocketDiscovery(m manage.IManage) *SocketDiscovery {
return &SocketDiscovery{IManage: m}
}
func (c *SocketDiscovery) Pr... |
//
// Package bitfinex implements the Connector, Ticker and Trader interfaces
// for the Bitfinex websocket API v2
//
package bitfinex
import (
"time"
"sync"
"strings"
"strconv"
"encoding/json"
"github.com/aglyzov/ws-machine"
"github.com/aglyzov/exchange-api"
)
func (_ *API) GetName() string {
return "Bitfi... |
package shardmaster
import (
"log"
"sort"
"sync"
"sync/atomic"
"time"
"../labgob"
"../labrpc"
"../raft"
)
const Debug = 0
func DPrintf(format string, a ...interface{}) (n int, err error) {
if Debug > 0 {
log.Printf(format, a...)
}
return
}
func DPrint(v ...interface{}) (n int, err error) {
if Debug >... |
package main
import "fmt"
func main() {
fmt.Println("Hello Golang!")
fmt.Println("Hello 2!")
fmt.Println("Hello 3!")
fmt.Println("Hello 4!")
fmt.Println("Hello 5!")
fmt.Println("Hello 6!")
fmt.Println("Hello 7!")
fmt.Println("Hello 8!")
}
|
package hello
import (
"fmt"
"github.com/TeamChii/hello-lambda/common"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
)
type Servicer interface {
HelloService(c echo.Context) (*HelloResponse, error)
}
type Service struct {
logger *zap.Logger
}
func NewService(logger *zap.Logger) *Service {
return &Service... |
// Original work Copyright 2018 Twitch Interactive, Inc. All Rights Reserved.
// Modified work Copyright 2018 MyGnar, 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. A copy of the License is
// located ... |
package main
import (
"fmt"
"go-taylor/calculator"
)
func main() {
var x float64
fmt.Print("x = ")
fmt.Scan(&x)
fmt.Print("e ^ x = ")
fmt.Println(calculator.Exp(x))
fmt.Print("ln x = ")
fmt.Println(calculator.Ln(x))
fmt.Print("e ^ (-x^2) = ")
fmt.Println(calculator.Norm(x))
fmt.Print("sin(x) = ")
fmt.P... |
package handler
import (
"context"
"errors"
"fmt"
"time"
"github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
)
// ModifySecureEmail 修改安全邮箱
func (j *JinmuIDService) ModifySecureEmail(ctx context.Context, req *proto.ModifySecureEmai... |
// Custom logger for printing error lists together with the filename and line
// number of the originating code, implemented on top of Go's own log package.
package main
import (
"log"
"os"
"strings"
)
type printlnFn func(*log.Logger, ...interface{})
var codeLogger = log.New(os.Stderr, "", 0)
// ... |
package ksqlparser
import "fmt"
func (p *parser) Error(expected string) error {
return fmt.Errorf("expected %s at line %d col %d, %s^", expected, p.line, p.col, p.sql[:p.i])
}
func (p *parser) SyntaxError() error {
return fmt.Errorf("syntax error at line %d col %d, %s^", p.line, p.col, p.sql[:p.i])
}
|
package app
import (
"context"
"testing"
"github.com/skos-ninja/truelayer-tech/svc/pokemon/services/pokeapi"
"github.com/skos-ninja/truelayer-tech/svc/pokemon/services/shakespeare/test"
"github.com/stretchr/testify/assert"
)
func TestGetShakespearePokemonDescriptionNotFound(t *testing.T) {
ctx := context.Back... |
package trace
import (
"context"
"github.com/labstack/echo"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"net/http"
"net/url"
)
type mwOptions struct {
opNameFunc func(r *http.Request) string
spanObserver func(span opentracing.Span, r *http.Request)
urlT... |
package clair
import (
"strconv"
"strings"
"github.com/coreos/clair/api/v1"
"github.com/coreos/pkg/capnslog"
"github.com/ContinuousSecurityTooling/clairctl/xstrings"
"github.com/spf13/viper"
"net/http"
)
var log = capnslog.NewPackageLogger("github.com/ContinuousSecurityTooling/clairctl", "clair")
var uri str... |
package lark
import "fhyx.online/lark-api-go/client"
type AuthContactResponse struct {
client.Error
Data struct {
AuthedDepartments []string `json:"authed_departments"`
AuthedEmployeeIDs []string `json:"authed_employee_ids"`
AuthedOpenIDs []string `json:"authed_open_ids"`
} `json:"data"`
}
func (acr *A... |
package main
import (
"bytes"
"encoding/binary"
"fmt"
"log"
)
func main() {
var num int64 = 1596 // 64位整数,8个字节
var buf bytes.Buffer
err := binary.Write(&buf, binary.BigEndian, num)
if err != nil {
log.Fatal()
}
bytes := buf.Bytes()
fmt.Println(bytes) // [0 0 0 0 0 0 0 15]
var decodingNum int64
err = b... |
// Copyright 2015 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 main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/rwcarlsen/goexif/exif"
"github.com/rwcarlsen/goexif/tiff"
)
var bucketName = "waldo-recruiting"
type PhotoReader struct {
svc *s3.S3
bucket *string
}
func NewReader() (*PhotoReader, error... |
package lib
import (
"errors"
"io"
"log"
"sync"
)
//实现一个有缓冲通道的资源池,可以管理在任意多个 goroutine之间的资源共享,比如网络连接和数据库连接等。
//每个 goroutine 可以向资源池里申请资源,然后使用完之后放回资源池里。
type Pool struct {
m sync.Mutex //互斥锁,这主要是用来保证在多个goroutine访问资源时,池内的值是安全的。
res chan io.Closer //有缓冲的通道,用来保存共享的资源
factory func(... |
// Package argsort implements a variant of the sort function that returns a slice of indices that would sort the array.
//
// The name comes from the popular Python numpy.Argsort function.
package argsort
import (
"reflect"
"sort"
)
// SortInto sorts s and populates the indices slice with the indices that would sor... |
package main
import (
"fmt"
"github.com/go-macaron/binding"
"github.com/go-macaron/cache"
"github.com/go-macaron/session"
"gopkg.in/macaron.v1"
"html/template"
"net/http"
)
//HTTPConfig has webserver config options
type HTTPConfig struct {
Port int `toml:"port"`
AdminUser string `toml:"adminu... |
package product
import (
"database/sql"
"fmt"
"github.com/atang152/go_webapp/config"
"net/http"
)
func Index(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
products, err := AllProduct()
if err != nil {
http.Erro... |
package api
import (
"fmt"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/rancher/go-rancher/api"
"github.com/rancher/longhorn-manager/types"
)
type BackupsHandlers struct {
man types.VolumeManager
}
func (bh *BackupsHandlers) ListVolume(w http.Response... |
package main
import "fmt"
func main() {
fmt.Println("Greg is cool!")
fmt.Println(sum_all_integers())
//fmt.Println(sum(abundant_numbers()))
//fmt.Println(proper_divisors(28))
//fmt.Println(sum(proper_divisors(28)))
//fmt.Println(sum_all_integers() - sum(abundant_numbers()))
fmt.Println(sum(abundant_sums(abund... |
// Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.
// A portable Winlink client for amateur radio email.
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"os/signal"
"... |
package service
import (
"github.com/Highway-Project/highway/config"
"github.com/Highway-Project/highway/pkg/service"
)
func NewBackends(specs []config.BackendSpec) ([]service.Backend, error) {
backends := make([]service.Backend, 0)
for _, spec := range specs {
backend := service.Backend{
Name: spec.Backen... |
package log
import (
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/sirupsen/logrus"
)
const (
LIMITS = 5
PREFIX = "application-csv2geojson-"
EXTENSION = ".log"
DIRECTORY = "tmp"
)
var (
AppLogger = Logger{}
)
func init() {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
path := file... |
package hls
import (
"common/httputils"
"fmt"
"io"
"net/url"
"os"
"path"
"sort"
"strings"
"sync"
"time"
)
const (
StreamTsCountMax = 200 //ts存放的数量;
StreamTsCountReduce = 100 //一次性删除的数量;
)
const (
ErrorCodeBase = iota + 1000
ErrorCodeM3u8DownloadFail
ErrorCodeM3u8FormatError
ErrorCodeTsDownloadRetr... |
package oss
type Bucket struct {
}
|
// Copyright 2023 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 driveapicollector
import (
"fmt"
"github.com/scjalliance/drivestream/resource"
drive "google.golang.org/api/drive/v3"
)
// MarshalDrive marshals the given team drive as a resource.
func MarshalDrive(d *drive.TeamDrive) (resource.Drive, error) {
created, err := parseRFC3339(d.CreatedTime)
if err != nil {... |
// Copyright 2018 Diego Bernardes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package flare
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestDocumentNewer(t *testing.T) {
Convey("Feature: Check if a docume... |
package main
import (
"fmt"
"math"
)
func isprime(n int) bool {
x := 2
for x < n {
if math.Mod(float64(n), float64(x)) == 0 {
return false
} else {
x++
}
}
return true
}
func main() {
sum := 0
x := 2
for x <= 1000000 {
if isprime(x){
sum += x
}
x++
}
f... |
// Copyright 2019-2023 The sakuracloud_exporter 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 appl... |
package status
import (
"github.com/gin-gonic/gin"
"github.com/wajox/gobase/internal/app/build"
"github.com/wajox/gobase/internal/web/controllers/apiv1"
"github.com/wajox/gobase/internal/web/render"
"net/http"
)
var (
_ apiv1.Controller = (*Controller)(nil)
)
// Controller is a controller implementation for s... |
// Copyright © 2018-2020 Wei Shen <shenwei356@gmail.com>
//
// 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 without limitation the rights
// to use, copy, mo... |
package main
import (
"crypto/hmac"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"math"
"math/rand"
)
var (
STRENGTH = "1_strength"
INTELLIGENCE = "2_intelligence"
WISDOM = "3_wisdom"
DEXTERITY = "4_dexterity"
CONSTITUTION = "5_constitution"
CHARISMA = "6_charisma"
)
type Trait str... |
/*
In this challenge, sort a list containing a series of dates given as strings. Each date is given in the format DD-MM-YYYY_HH:MM:
"12-02-2012_13:44"
The priority of criteria used for sorting will be:
Year
Month
Day
Hours
Minutes
Given a list lst and a string mode, implement a function that re... |
package utils
import "github.com/go-gomail/gomail"
// SendMailParam 邮件参数
type SendMailParam struct {
ToMail string
ToName string
Title string
Content string
}
// SendMail 发邮件
func SendMail(p SendMailParam) (err error) {
m := gomail.NewMessage()
m.SetHeader("From", "545397649@qq.com") // 发件人
m.SetHeader("T... |
package rest
import (
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/kataras/iris/v12"
)
// ModifySecureEmailRequest 修改安全邮箱请求
type ModifySecureEmailRequest struct {
NewEmail string `json:"new_email"` ... |
package main
/**
109. 有序链表转换二叉搜索树
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
```
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
```
*/
/*
咋就这么烦链表题呢
ERROR
*/
/**
* Definition for a binar... |
package main
import (
"flag"
"fmt"
"os"
"github.com/FactomProject/factom"
)
func main() {
var (
faAddress = flag.String("fa", "", "Factoid public key")
n = flag.Int("n", 100, "Number of addresses")
filename = flag.String("file", "addresses.txt", "File to output addresses")
amount = flag.Int(... |
// it should print only those items which don't have the same successor
// 'a' 'b' 'a' 'a' 'a' 'c' 'd' 'e' 'f' 'g' => 'a' 'b' 'a' 'c' 'd' 'e' 'f' 'g'
package main
import "fmt"
func main() {
a := []string{"a", "b", "a", "a", "a", "c", "d", "e", "f", "g"}
first := ""
for _, s := range a {
if first != s {
fmt.Pr... |
package main
import (
"bufio"
"encoding/json"
"fmt"
"net"
"os"
"sync/atomic"
)
func main() {
stdin := os.Stdin
reader := bufio.NewReader(stdin)
stdout := os.Stdout
os.Stdout = os.Stderr
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "argument invalid")
}
logApi := os.Args[1]
conn, err := net.Dial("unix"... |
package inmemory_test
import (
"testing"
"github.com/Tinee/go-graphql-chat/inmemory"
"github.com/Tinee/go-graphql-chat/domain"
)
func Test_messagesInMemory_Create(t *testing.T) {
c := NewClient()
repo := c.MessageRepository()
m, err := repo.Create(domain.Message{
ReceiverID: "Foo",
SenderID: "Bar",
T... |
//go:generate go run generate.go insertionsort.go
//go:generate goimports -w ../../insertionsort/
//go:generate gofmt -w ../../insertionsort/
package main
const PACKAGE = "insertionsort"
const TEMPLATE = `
// {{.FuncName}} sorting slice of {{.Name}}
func {{.FuncName}}(in []{{.Name}}) {
var i, j int
var key {{.... |
package service
import (
"context"
"go.uber.org/zap"
"mix/test/pb/core/transaction"
)
func (p *Transaction) CreateAccount(ctx context.Context, in *transaction.CreateAccountInput, out *transaction.AccountOutput) error {
db := p.db.NewSession()
logger := p.logger.With(zap.String("caller", "CreateAccount"))
defer ... |
package main
import "fmt"
import s "strings"
func main() {
messages := make(chan string)
var message string
fmt.Scanln(&message)
go func() { messages <- message }()
go func() {
msg := <- messages
if s.ToLower(msg) == "ping" {
fmt.Println("PONG")
}
}()
var exit... |
package main
import (
"context"
"flag"
"fmt"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/sirupsen/logrus"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"google.golang.org/grpc/reflection"
"google.golang.org/protobuf/types/known/timestamppb"
"net/http"
"strings"
"time"
"github.... |
package api
import (
"bytes"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/BurntSushi/toml"
"github.com/hashicorp/raft"
"github.com/robustirc/robustirc/internal/config"
"github.com/robustirc/robustirc/internal/robust"
)
func (api *HTTP) configRevision() uint64 {
i := api.ircServer()
i.ConfigMu.RLock... |
package config
import (
"fmt"
)
var (
defaults = NewValues("defaults", nil)
)
//Set a default value to use if value is not found in any config engine
//Fails when already defined (which may be from a config engine or default previously set)
func SetDefault(name string, defaultValue interface{}) error {
if defined... |
package ankaboot
// Greatly inspired by Rob Pike's talk on Lexical Analysis in Go
// and borrowed a lot of the code from slide, to get it to work.
// Will require to modify the code to be more suitable for my own
// use case.
//
type itemType int
// Define all of the 'items' the lexer will need to lex.
const (
itemE... |
package api
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
ISBN string `json:"isbn"`
}
var books map[string]Book
func ToJSON(b Book) ([]byte, error) {
return json.Marshal(b)
}
func FromJSON(bJson []byte) (*Bo... |
package models
import (
. "2019_2_IBAT/pkg/pkg/models"
"github.com/google/uuid"
)
type InChatMessage struct {
ChatID uuid.UUID `json:"chat_id" db:"id"`
OwnerInfo AuthStorageValue `json:"-" db:"-"`
Timestamp string `json:"timestamp" db:"id"`
Te... |
package main
import (
"testing"
"github.com/ubinte/livego/app"
"github.com/ubinte/livego/protocol/rtmp"
)
func TestStartHttpflvServer(t *testing.T) {
app.AddApp("live").AddChannelKey("insecure_channel_key", "movie")
stream := rtmp.NewRtmpStream()
go StartRtmpServer(stream, ":1935") // push rtmp://127.0.0.1:193... |
package cmd
import (
"github.com/danhale-git/craft/craft"
"github.com/danhale-git/craft/internal/logger"
"github.com/spf13/cobra"
)
// NewListCmd returns the list command which lists running and backed up servers.
func NewListCmd() *cobra.Command {
listCmd := &cobra.Command{
Use: "list <server>",
Short: "Li... |
package mutexrw
import (
"fmt"
"log"
"math/rand"
"runtime"
"sync"
"testing"
"time"
)
// counter 代表计数器
type counter struct {
num uint //计数
mu sync.RWMutex //读写锁
}
// number 会返回当前的计数
func (c *counter) number() uint {
c.mu.RLock()
defer c.mu.RUnlock()
return c.num
}
func (... |
package reddit
import (
"net/http"
"io/ioutil"
"strings"
"encoding/json"
"log"
"fmt"
"os"
)
const (
RedditTokenEndpoint = "https://www.reddit.com/api/v1/access_token"
)
type Application struct {
ClientId string
ClientSecret string
UserAgent string
}
func NewApp(clientId string, clientSecret string, us... |
package quacktors
import (
"github.com/Azer0s/quacktors/mailbox"
"github.com/Azer0s/quacktors/metrics"
"github.com/opentracing/opentracing-go"
"sync"
)
//The Actor interface defines the methods a struct has to implement
//so it can be spawned by quacktors.
type Actor interface {
//Init is called when an Actor is... |
package session
import (
"go/internal/pkg/api/app/request"
"go/internal/pkg/response"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *sessionHandler) DeleteHandler(ctx *gin.Context) {
var req request.SessionRequest
claimemail := ctx.GetString("userEmail")
req.Email = claimemail
if err := ctx.ShouldBindJS... |
package templatescompiler_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
boshlog "github.com/cloudfoundry/bosh-agent/logger"
fakeblobs "github.com/cloudfoundry/bosh-agent/blobstore/fakes"
fakecmd "github.com/cloudfoundry/bosh-agent/platform/commands/fakes"
fakesys "github.com/cl... |
package web
import (
"ChangeInspector/logservice"
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
/*CommitsHandler ...*/
type CommitsHandler struct {
logService *logservice.LogService
}
func (handler CommitsHandler) register(router *mux.Router) {
router.HandleFunc("/commits/{hash}", func(w http.Response... |
/**
*
*
Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repeti... |
package main
import (
"context"
"fmt"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
gr... |
package longestCommonPrefix
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
if len(strs) == 1 {
return strs[0]
}
ret := strs[0]
last := len(ret)
label:
for _, str := range strs[1:] {
i := 0
for ; i < last && i < len(str); i++ {
if str[i] != ret[i] {
last = i
c... |
/////////////////////////////////////////////////////////////////////
// arataca89@gmail.com
// 20210417
//
// func Count(s, substr string) int
//
// Retorna o número de ocorrências de substr em s.
// Se substr for "" retorna 1 + o número de Unicode code points em s.
//
// Fonte: https://golang.org/pkg/strings... |
package duplicateobj
import (
"fmt"
"gopkg.in/oleiade/reflections.v1"
)
func getObjFieldString(fieldsToExtract []string, object interface{}) string {
output := ""
for _, fieldName := range fieldsToExtract {
value, _ := reflections.GetField(object, fieldName)
output = output + ">>" + fmt.Sprintf("%v", value)
... |
// Copyright Project Harbor 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 t... |
package main
import "fmt"
type Invoker interface {
// 需要实现Call方法
Call(interface{})
}
type FuncCaller func(interface{})
// 实现 Invoker
func (f FuncCaller) Call(p interface{}) {
f(p)
}
var invoker Invoker
func main() {
invoker = FuncCaller(func(v interface{}) {
fmt.Println("from function", v)
})
invoker.Cal... |
package config
import(
"encoding/json"
"io/ioutil"
"util"
"runtime"
"path/filepath"
"fmt"
//"os"
)
type ServiceAPI struct {
Key string `json: "key"`
Method string `json: "method"`
Uri string `json: "uri"`
Data string `json: "data"`
}
type ServiceItem struct {
Id strin... |
/*
A simple traceroute program written in Go.
*/
package main
import (
"flag"
"fmt"
"net"
"os"
"syscall"
"time"
)
const (
HOST = "0.0.0.0"
SEND_PORT = 33333
RECV_PORT = 0
TIMEOUT = 5000
)
type ReturnArgs struct {
ok bool
done bool
addr string
ip string
elapsed float64
}
func ma... |
package main
import (
// "log"
"fmt"
"net/http"
)
func HandleShutdown(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Handle shutdown")
}
|
package main
import (
"html/template"
)
var userInfoTemplate = template.Must(template.New("").Parse(`
<html><body>
This app is now authenticated to access your Google user info. Your details are:<br />
{{.}}
</body></html>
`))
type ErrorPage struct {
Code int
Message interface{}
}
var errorTemplate = templat... |
package golang
const (
AuthService = "examples.blog.service.auth"
UserService = "examples.blog.service.user"
)
const (
ApiGateway = "examples.blog.api.gateway"
) |
package helpers
import (
"math"
"strconv"
)
func GetAvatar2(level int) string {
ret := "avatar2"
n100 := math.Floor(float64(level)/100) * 100
if n100 >= 100 {
ret += " lvl_" + strconv.FormatFloat(n100, 'f', 0, 64)
n10 := math.Floor(float64(level)/10) * 10
n10String := strconv.FormatFloat(n10, 'f', 0, 6... |
package main
import (
"crypto/ecdsa"
"crypto/rand"
"errors"
"fmt"
"math/big"
"testing"
)
const (
TEST_PRIVATE_KEY = "fe90f04022ee37dfb4ccae2c9d2610932a1c7bd8f92b0a2e05cf8c7031ad5b1c"
TEST_PUBLIC_KEY = "023f00e77837b341841f587385594951d65179364c2d435d44457df19797012975"
)
func TestSignatureCommand(t *testing... |
package main
import (
"fmt"
)
func main() {
var n, m int
fmt.Scanf("%d %d\n", &n, &m)
v := make([]uint64, m)
for i := 0; i < m; i++ {
fmt.Scanf("%d", &(v[i]))
}
var steps,pos uint64
pos = 1
steps = 0
for i := 0; i < m; i++ {
if v[i] >= pos {
steps += v[i] - pos
} else {
steps += u... |
package storage
import (
"github.com/biezhi/gorm-paginator/pagination"
md "github.com/ebikode/eLearning-core/model"
)
// DBJournalStorage encapsulates DB Connection Model
type DBJournalStorage struct {
*MDatabase
}
// NewDBJournalStorage Initialize Journal Storage
func NewDBJournalStorage(db *MDatabase) *DBJourna... |
package main
import (
"context"
"log"
"net"
pb "github.com/morimolymoly/grpc-is-fun/helloworld/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
port = ":8100"
)
// HelloWorldServer ... implements pb.HelloWorldServiceServer
type HelloWorldServer struct {
}
// SayHello ... implements... |
package g
import (
//"github.com/elves-project/agent/src/thrift/scheduler"
"sync"
"time"
)
type StatGInfo struct {
Mode string
Asset string
Ip string
Uptime string
Hbtime string
Ver string
Apps map[string]string
}
type sIns struct {
Time string
ID string
Type string
Mode s... |
/*
Copyright 2019 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 segment
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
var (
mux *http.ServeMux
client *Client
server *httptest.Server
)
const (
testToken = "test-token"
testWorkspace = "test-workspace"
)
func setup() {
mux = http.NewServeMux()
server = ht... |
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
starting := strings.Split("17,1,3,16,19,0", ",")
var spoken []int
lastSeen := map[int]int{} // number: index
lastSeen2 := map[int]int{} // number: index
for index, s := range starting {
i, _ := strconv.Atoi(s)
lastSeen[i] = index + 1
spoke... |
//
// Copyright (c) 2018
// Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//
package cli
import (
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/fatih/color"
)
var (
// Limit query parameter
Limit uint = 10
// Offset query parameter
Offset uint
)
func flush(i interface{}) {
fmt.Printf("%s", color... |
/*
Copyright 2015 Crunchy Data Solutions, 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 main
import (
"log"
"os"
"os/signal"
"syscall"
"github.com/dmitry-vovk/csv-chg-go/api"
"github.com/dmitry-vovk/csv-chg-go/config"
"github.com/dmitry-vovk/csv-chg-go/source"
"github.com/dmitry-vovk/csv-chg-go/worker"
)
func main() {
// Load configuration
cfg := config.MustLoad()
// Build worker ins... |
package resources
import (
"os"
"path"
"testing"
)
func TestConf(t *testing.T) {
wd, _ := os.Getwd()
fileName := path.Join(wd, "test.log")
Conf(fileName)
Logger.Debugf("hello debug.")
Logger.Infof("hello info.")
}
|
package client
import (
exchange "github.com/preichenberger/go-coinbase-exchange"
)
type GDAXClient struct {
Client *exchange.Client
}
func NewGDAXClient(client *exchange.Client) GDAXClient{
return GDAXClient{client}
}
|
package main
import "fmt"
/**
Golang中的面向对象
1、封装:通过可见性原则来保证
2、继承:基于组合来实现。内嵌结构体,内嵌结构体
3、多态:基于接口来实现。松耦合的正交,隐式实现接口,鸭式辩形
*/
type Seller interface {
sell() string
}
type BusinessMan interface {
Seller
purchase() string
}
type FruitSeller struct {
fruitType string
}
type ShoeSeller struct {
sh... |
package main
import (
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
"fmt"
)
// SimpleAsset implements a simple chaincode to manage an asset
type Simpleasset struct{}
func (t *Simpleasset) Init(stub shim.ChaincodeStubInterface) peer.Response{
args:= stub.GetStri... |
package main
import (
"container/list"
"flag"
"fmt"
"io/ioutil"
"strings"
)
func main() {
flag.Parse()
testWords, dictionary := parseInputFile(flag.Args()[0])
for _, word := range testWords {
fmt.Println(sizeOfSocialNetwork(word, dictionary))
}
}
// file parsing
func parseInputFile(filename string) ([]... |
package rpc
import (
"context"
v1 "github.com/tinkerbell/pbnj/api/v1"
"github.com/tinkerbell/pbnj/pkg/logging"
"github.com/tinkerbell/pbnj/pkg/task"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// TaskService for retrieving task details.
type TaskService struct {
Log logging.Logger
... |
package main
import (
"fmt"
"time"
)
/**
* created: 2019/5/8 10:24
* By Will Fan
*/
func main() {
var ch chan int
for i:= 0; i < 3; i++ {
go func(idx int) {
ch <- (idx + 1)*2
}(i)
}
//
fmt.Println("result:", <-ch)
time.Sleep(2*time.Second)
}
|
package controller
import "github.com/therecipe/qt/core"
var Controller *ThemeController
type ThemeController struct {
core.QObject
_ func() `constructor:"init"`
_ string `property:"name,auto,changed"`
_ string `property:"accent,auto,get"`
_ string `property:"nextAccent,auto,get"`
_ string ... |
package examples
import (
"fmt"
"io/ioutil"
"os"
)
func StartFile() {
fmt.Println("\nРабота с файлами")
create()
openAndRead()
readFile()
}
func create() {
f, err := os.Create("exp-1")
defer f.Close()
if err != nil {
panic(err)
}
count, err := f.WriteString("Hello world")
if err != nil {
fmt.Print... |
package rest
import (
jwtmiddleware "github.com/jinmukeji/jiujiantang-services/pkg/rest/jwt"
analysispb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/analysis/v1"
corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
subscriptionpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partne... |
package collectors
import (
"encoding/json"
"errors"
"fmt"
"time"
cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger"
lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric"
"github.com/ClusterCockpit/go-rocm-smi/pkg/rocm_smi"
)
type RocmSmiCollectorConfig struct {
ExcludeMetrics [... |
package session
import (
"go/internal/pkg/api/app/request"
"go/internal/pkg/response"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *sessionHandler) CreateHandler(ctx *gin.Context) {
var req request.SessionRequest
// claimid := ctx.GetInt("userId")
claimname := ctx.GetString("userName")
claimemail := ctx.... |
package connectors
import (
"io"
"fmt"
"errors"
"encoding/json"
"net/http"
log "github.com/sirupsen/logrus"
)
var (
// define base URL for google API
baseApiURL = "https://maps.googleapis.com/maps/api/place/details/json"
// define custom errors
ErrInvalidAPIResponse = errors... |
package blog
// Engagement represents social network engagement of the object
type Engagement struct {
// Total object shared counter
ShareCount int `bson:"-" json:"shareCount" graphql:"shareCount"`
}
|
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package nydussdk
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"time"
"github.com/pkg/errors"
"github.com/dragonflyoss/image-service/contrib/nydus-snapshotter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.