text stringlengths 11 4.05M |
|---|
package proxy
//错误码
const (
EC_LSROUTE_IS_NIL = 20001
EC_HSROUTE_IS_NIL = 20002
EC_GSROUTE_IS_NIL = 20003
EC_LSROUTE_IS_UNAUTHED = 20004
EC_HSROUTE_IS_UNAUTHED = 20005
EC_GSROUTE_IS_UNAUTHED = 20006
)
|
package main
import "todos/model"
// TodoService interface
type TodoService interface {
All() ([]model.Todo, error)
Create(todo *model.Todo) error
FindByID(id int) (*model.Todo, error)
DeleteByID(id int) ([]model.Todo, error)
Update(id int, body string) (*model.Todo, error)
}
// SecretService interface
type Sec... |
package ppgo
import (
"github.com/labstack/echo"
)
func PpgoRun() {
//初始化ECHO路由
NewEcho()
// Routes路由
Echo.Get("/", func(c echo.Context) error {
Response := NewResponse(c)
return Response.RetSuccess("hello,world!")
})
//开启服务
RunFasthttp(":1333")
} |
package rulesets
const (
// CreateRuleSetEndpoint is a string representation of the current endpoint for creating ruleset
CreateRuleSetEndpoint = "v1/ruleset/createRuleset"
// GetAppliedRuleSetEndpoint is a string representation of the current endpoint for getting applied ruleset
GetAppliedRuleSetEndpoint = "v1/ru... |
package routes
import (
"bytes"
"crypto/sha256"
SU "github.com/abaft/LUUScoreKeeper/scoreutils"
TP "github.com/abaft/LUUScoreKeeper/template"
"github.com/boltdb/bolt"
"github.com/kataras/iris"
"github.com/kataras/iris/sessions"
"log"
)
var (
cookieNameForSessionID = "LUUScoreKeeper"
sess =... |
package main
import (
"log"
"net/http"
)
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func main() {
graph := Graph{}
graph.Render()
fs := htt... |
package main
import "fmt"
// You can run go file by command "go run hello.go"
func main(){
/* This is my first sample program. */
fmt.Printf("Hello Golang!\n")
} |
package lnglat
// LngLat ... 緯度経度型
type LngLat struct {
// Longitude ... 経度(lamda)
Longitude float64
// Latitude ... 緯度(phi)
Latitude float64
}
|
package main
import (
"fmt"
"github.com/common/message"
"github.com/utils"
"net"
"server/process"
)
type Processor struct {
Conn net.Conn
Buf [8096]byte
}
func (this *Processor)ProcessHandle() {
tf := &utils.Transfer{
Conn: this.Conn,
}
mes,err:=tf.ReadPkg()
fmt.Println("mes.type=",mes.Type)
fmt.Print... |
package builder
import (
"errors"
"fmt"
"gengine/context"
"gengine/internal/base"
parser "gengine/internal/iantlr/alr"
"gengine/internal/iparser"
"gengine/internal/tool"
"github.com/antlr/antlr4/runtime/Go/antlr"
"sort"
"strings"
"sync"
)
type RuleBuilder struct {
Kc *base.KnowledgeContext
Dc *context.Da... |
package reconnect
import (
"context"
"io"
"math/rand"
"sync"
"testing"
"time"
bhost "gx/ipfs/QmSgtf5vHyugoxcwMbyNy6bZ9qPDDTJSYEED2GkWjLwitZ/go-libp2p/p2p/host/basic"
u "gx/ipfs/QmNohiVssaPw3KVLZik59DBVGTSm2dGvYT9eoXt5DQ36Yz/go-ipfs-util"
swarmt "gx/ipfs/QmTJCJaS8Cpjc2MkoS32iwr4zMZtbLkaF9GJsUgH1uwtN9/go-libp... |
package types
var AndEmptyString = ""
var AndTrue = true
var AndFalse = false
//when you have a slice of string
// you want to remove a specific value from an index
func RemoveIndex(s []string, index int) []string {
return append(s[:index], s[index+1:]...)
}
// when you want to find the index of the
func FindIndex(... |
package main
import (
"errors"
"fmt"
"time"
)
// ErrInput - If inputs are invalid
var ErrInput = errors.New("Not items in the array add up to target")
// Nums - a single node that composes the list
type Nums []int
type Targets []int
type NumToIndex map[int]int
func timeTrack(start time.Time, name string) {
elap... |
/*
With the help of Before() and After() and Equal(), function we can compare the time
as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparison.
Functions Used: These functions compares the times as seconds.
Before(temp) – This function is used to check if t... |
package controller
import "fmt"
type Hub struct {
clients map[*client]bool
broadcast chan []byte
register chan *client
unregister chan *client
content string
}
func NewHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *client),
unregister: make(chan *client),
clients... |
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
)
func main() {
all := flag.Bool("all", false, "make run scripts for all folders")
source := flag.String("source", "sources", "relative path to folder containing source code folders")
args := flag.Args()
flag.Usage = func() {
fmt.Fprintf(flag.CommandL... |
package options
// FilelistPolicyOptions is the option aggregate structure for options for
// policy apply operations in the filelist package.
type FilelistPolicyOptions struct {
PolicyOptions PolicyOptions
ExcludePathPatterns []string
}
func (f *FilelistPolicyOptions) Apply(opts []FilelistPolicyOptioner) *Fi... |
package main
import "fmt"
// https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/
func findDisappearedNumbers(nums []int) []int {
N := len(nums)
if N == 0 {
return nil
}
swap := func(i, j int) { nums[i], nums[j] = nums[j], nums[i] }
for i := 0; i < N; {
if nums[i] == i+1 || nums[i] ==... |
package models
type Recipe struct {
ID int64
Title string
Description string
IngredientsList []string
} |
// Copyright 2019-present 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 agr... |
package model
import "github.com/shopspring/decimal"
// Commission represents a service charge assessed by a broker or investment advisor in return for providing investment
// advice and/or handling the purchase or sale of a security.
type Commission struct {
CommissionID int `gorm:"primary_key;AUTO_INCREMENT"`
Fir... |
package main
import "testing"
func callGenerateTokenTest(t *testing.T) {
}
|
// Package pixelclient implements a client that sends packets to a PixelPusher
// device.
package pixelclient
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"time"
"github.com/danjacques/pixelproxy/applications/pixelproxy/web"
"github.com/danjacques/pixelproxy/util"
"github.com/... |
package main
import (
"fmt"
stdLog "log"
"os"
"time"
"github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
)
var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
func main() {
mqtt.DEBUG = s... |
package main
import (
"music-saas/core"
"music-saas/global"
"music-saas/initialize"
)
func main() {
global.VIPER = core.Viper()
global.LOG = core.Zap()
global.DB = initialize.Gorm()
initialize.MysqlTables(global.DB)
db, _ := global.DB.DB()
defer db.Close()
core.RunServer()
}
|
package platform
import (
"encoding/json"
"io/ioutil"
"github.com/pkg/errors"
)
func LoadConfigFromJSONFile(filename string, configType interface{}) error {
b, err := ioutil.ReadFile(filename)
if err != nil {
return errors.Wrapf(err, "Error loadding file %s", filename)
}
return errors.Wrapf(json.Unmarshal(b... |
package database
import (
"log"
"github.com/solrac97gr/cryptoAPI/models"
)
func SaveEncryptMessage(encryptionKey string, encryptedText string) string {
ref := DatabaseClient.NewRef("/")
textRef := ref.Child("text")
newText, err := textRef.Push(FirebaseCtx, nil)
if err != nil {
log.Fatalln("Error pushing chil... |
package autoscaler
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
)
type EC2Tag struct {
Key string `yaml:"Key" validate:"required"`
Value string `yaml:"Value" validate:"required"`
}
type EC2Tags []EC2Tag
func (ts EC2Tags) SDK() []*ec2.Tag {
ret := []*ec2.Tag{}
for _, t := ... |
package web
import (
"net/http"
"github.com/rvillablanca/goweb/session"
"github.com/rvillablanca/goweb/template"
)
// Context representa toda la información requerida procesar una petición HTTP.
type Context struct {
Session *session.Session
Response http.ResponseWriter
Request *http.Request
}
// NewRendere... |
// Copyright 2015 Globo.com. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package config provide configuration facilities, handling configuration
// files in yaml format.
//
// This package has been optimized for reads, so functions wri... |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package zbar
// "color" of element: bar or space.
const (
ZBAR_SPACE = iota // light area or space between bars
ZBAR_BAR // dark area or colored bar segment
)
// zbar_symbol_type_t
// decoded symbol type.
const (
ZBAR_NONE = 0 /**< no symbol decoded */
ZBAR_PARTIAL = 1 /**< intermediate st... |
package fileutil
import (
. "github.com/101loops/bdd"
)
var _ = Describe("File Utility", func() {
It("checks if file exists", func() {
Check(Exists("README.md"), IsTrue)
Check(Exists("nonsense"), IsFalse)
})
})
|
package glman
import (
"runtime"
"tetra/internal/gl"
)
// MText is text model
type MText interface {
Render()
Colors() []Color
SetColors(c ...Color)
DrawEdge() bool
SetDrawEdge(b bool)
Text() string
}
type mText struct {
s string
f *texFont
gs []*glyph
vbo *Res
segs [][3]uint32 // [0]=texture,... |
package main
import "fmt"
func mergeSort(a []int) []int {
if len(a) <= 1 {
return a
}
left := make([]int, 0)
right := make([]int, 0)
m := len(a) / 2
for i, x := range a {
switch {
case i < m:
left = append(left, x)
case i >= m:
right = append(right, x)
}
}
left = ... |
package keva
type bucketCacheTrie struct {
entry *bucketCacheEntry
parent *bucketCacheTrie
children map[string]*bucketCacheTrie
}
func (t *bucketCacheTrie) Find(path bucketPath) *bucketCacheEntry {
node := t
for step, next := path.Step(); step != ""; step, next = next.Step() {
child, ok := node.children[... |
package parens
import (
"fmt"
"io/ioutil"
"strings"
"github.com/spy16/parens/parser"
)
// New initializes new parens LISP interpreter with given env.
func New(scope parser.Scope) *Interpreter {
exec := &Interpreter{
Scope: scope,
Parse: parser.Parse,
DefaultSource: "<string>",
}
loadFil... |
package jsonv
import (
"bytes"
"reflect"
"testing"
)
type simpleStruct struct {
Captcha string
Fullname string
}
func Test_ParseSimpleSuccess(t *testing.T) {
cases := []struct {
schema SchemaType
json string
want interface{}
}{
{Integer(), "123", int64(123)},
{Boolean(), "true", true},
{
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 nsopts
import (
"flag"
"os"
)
type Opts struct {
hostname string
rootfs string
netsetgo string
}
func NewOpts() Opts {
o := Opts{}
flag.StringVar(&o.hostname, "hostname", "go-containerized", "hostname inside container")
flag.StringVar(&o.rootfs, "rootfs", "/tmp/go-containerized/rootfs", "path to th... |
package main
import "fmt"
func location(name, city string) (string, country string) {
switch city {
case "New York", "LA", "Chicago":
country = "North America"
default:
country = "Unknown"
}
return name, country
}
func main() {
name, country := location("Matt",... |
package logentry
import (
"fmt"
"time"
"github.com/danielchatfield/go-chalk"
"github.com/danielchatfield/go-indicator"
)
// Status represents the status of the command
type Status int
// The supported statuses
const (
RUNNING Status = iota
SUCCESS
FAILURE
)
// Command is a log entry that represents the runn... |
package regex
import (
"regexp"
)
//Subexp returns the subexp with name subexp from target or "" if it does not exist.
func Subexp(r *regexp.Regexp, target string, subexp string) (val string) {
matches := r.FindStringSubmatch(target)
for i, name := range r.SubexpNames() {
if i > len(matches) {
return
}
if... |
package database
import (
"context"
"database/sql"
"fmt"
"time"
"rest_server/pkg/errors"
"github.com/lib/pq"
_ "github.com/lib/pq"
"github.com/sirupsen/logrus"
"golang.org/x/xerrors"
)
type PostgresDB struct {
User string
Password string
Host string
Port string
Name string
Connection... |
/*
* Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
package handler
import (
"context"
"errors"
"fmt"
"github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
)
// UserModifySecureQuestions 修改密保
func (j *JinmuIDService) UserModifySecureQuestions(ctx context.Context, req *proto.UserModify... |
package db
import (
"bcdb/config"
"testing"
)
func TestCalculationActiveFileNumber(t *testing.T){
db := NewDb(config.Db.DataDir)
number := db.Store.CalculationActiveFileNumber()
t.Log(number)
}
func TestAdd(t *testing.T) {
db := NewDb(config.Db.DataDir)
_, err := db.Store.Add("name", "dsadsa2321", 0)
if err ... |
package tools
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"time"
)
func OpenDB(service string) *gorm.DB {
//TODO get config by service
//TODO connection pool or prevent to build connection every time
db, err := gorm.Open(getConfig(""))
if err != nil {
panic(err)
}
// Migr... |
/*
* @lc app=leetcode.cn id=146 lang=golang
*
* [146] LRU缓存机制
*/
// @lc code=start
package main
import "fmt"
func main() {
a := Constructor(2)
a.Put(1,1)
// a.Print()
a.Put(2,2)
a.Print()
b := a.Get(1)
fmt.Printf("get 1 is %d\n", b)
a.Put(3,3)
a.Print()
a.Put(3,6)
a.Print()
c := a.Get(1)
fmt.Printf(... |
package simulation
import "github.com/cosmos/cosmos-sdk/types/module"
// RandomizedGenState generates a random GenesisState for HTLC
func RandomizedGenState(simState *module.SimulationState) {}
|
/*
Copyright 2019 Dmitry Kolesnikov, 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 law... |
package helpers
import (
"testing"
)
func TestInValidUrl(t *testing.T) {
t.Log("Running : test url validity")
testCasesInvalid := []string{
"www.google.com",
"google.com",
}
for _, each := range testCasesInvalid {
if IsValidUrl(each) {
t.Errorf("Failed: url validation: %s", each)
}
}
}
func TestVa... |
package logs
import (
"testing"
"time"
)
func TestConsoleLog(t *testing.T) {
log := NewLogger("test", 100)
log.SetAppender("console", `{"level":0,"prefix":"[cdc]"}`)
//time.Sleep(time.Second * 2)
log.Trace("trace")
log.Debug("debug")
log.Info("info")
//log.Close()
}
func TestFileLog(t *testing.T) {
log := N... |
package html
import (
"bytes"
"github.com/elliotchance/gedcom"
"github.com/elliotchance/gedcom/html/core"
"io"
)
type IndividualCompare struct {
comparison *gedcom.IndividualComparison
filterFlags *gedcom.FilterFlags
progress chan gedcom.Progress
compareOptions *gedcom.IndividualNodesCompareOptio... |
package sieve
import (
"github.com/ActiveState/log"
)
// TODO: somehow merge this redundant struct with EventParser.
type EventParserSpec struct {
Substring string `json:"substring"`
Re string `json:"regex"`
Sample string `json:"sample"`
Format string `json:"format"`
Severity string `jso... |
package main
import (
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var coll *mgo.Collection
var sleep = time.Sleep
var logFatal = log.Fatal
var logPrintf = log.Printf
var httpListenAndSe... |
package cfb
import "testing"
func TestEncryptSame(t *testing.T) {
samples := []struct {
secret string
iv string
str string
result string
err string
}{
{"secret key", "kd23w[qDn.5+2/Ok", "123456", "17d48e94c980", ""},
{"secret key", "kd23w[qDn.5+2/Ok", ".", "08", ""},
{"secret key", "kd23w[... |
package main
import "fmt"
func RmoveBack()
func main() {
a := []int{1,2,3,4,5,6,7,8,9,10}
b := a[4,8]
b[0] =1
b[1] =2
fmt.Prinln(a)
} |
package main
import (
"bufio"
"fmt"
"os"
"strings"
"strconv"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Simple shell")
fmt.Println("------------------------")
for {
fmt.Print("-> ")
text, _ := reader.ReadString('\n')
text = string... |
// ˅
package main
// ˄
type Item interface {
ToHTML() string
// ˅
// ˄
}
// ˅
// ˄
|
package main
//go:generate ./doc.sh
import (
"os"
"os/signal"
"syscall"
log "github.com/Sirupsen/logrus"
"github.com/brocaar/lora-gateway-bridge/backend/thethingsnetwork"
"github.com/brocaar/lora-gateway-bridge/gateway"
"github.com/brocaar/lorawan"
"github.com/codegangsta/cli"
)
var version string // set by... |
package exec
import (
"github.com/stretchr/testify/mock"
)
type MockExecer struct {
mock.Mock
}
|
package helper
import (
"bytes"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"strings"
)
// LoadFile does essentially what it says it does. It loads a file and transforms it into a
// two dimensional array of blocks of four bytes, without whitespaces. This is needed for further
// processing
func LoadFile(file string... |
package main
import (
"mysql_byroad/model"
"time"
log "github.com/Sirupsen/logrus"
"github.com/nsqio/go-nsq"
)
/*
任务对应的nsq consumer
*/
type TaskConsumer struct {
task *model.Task
consumer *nsq.Consumer
config *nsq.Config
}
func NewTaskConsumer(task *model.Task) (*TaskConsumer, error) {
config := nsq.N... |
package database
import (
"fmt"
"log"
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/kazetora/evermos-assignment/problem_1_ecommerce/models"
)
var db *gorm.DB
// Setup setup db connection
func Setup() {
var err error
dbSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset... |
package core
import (
"strings"
"encoding/json"
)
type Responder struct {
typeOf string
response string
mode string
}
func (rs *Responder) Response(r []byte) (interface{}, error) {
var jsonRes map[string]map[string]interface{}
json.Unmarshal(r, &jsonRes)
return jsonRes["result"]["speech"], nil
}
func (rs *... |
package redis
import (
"errors"
"github.com/go-redis/redis"
"sync"
)
const (
ReadStrategySlaveOnly = iota + 1
ReadStrategyClosestNode
ReadStrategyRandomNode
)
type ClusterConfig struct {
Addrs []string `toml:"addrs" json:"addrs"`
Password string `toml:"password" json:"password"`
ReadStrategy in... |
// Copyright 2016-2017 The psh Authors. All rights reserved.
package psh
import (
"testing"
)
func TestGetSegmentsList(t *testing.T) {
var tests = []struct {
input string
expected int
}{
{"", 0},
{"a,b", 2},
{"a,,c", 2},
}
for _, tt := range tests {
output := getSegmentsList(tt.input)
if len(out... |
package models
import "time"
type FactorAttribute struct {
FactorAttributeId int `json:"attributeId,omitempty" db:"AttributeId"`
FactorId int `json:"attributeEnumId" db:"AttributeEnumId"`
SourceId int `json:"sourceId" db:"SourceId"`
Value float32 `json:"value" db:"Value"`... |
package ble
import (
"crypto/ecdsa"
"encoding/hex"
"fmt"
"github.com/godbus/dbus/v5"
"github.com/jarijaas/openssl"
"github.com/muka/go-bluetooth/api/service"
"github.com/muka/go-bluetooth/bluez"
"github.com/muka/go-bluetooth/bluez/profile/agent"
"github.com/muka/go-bluetooth/bluez/profile/device"
"github.com... |
package util
import (
"errors"
"strings"
)
var (
ErrEmailFormat = errors.New("invalid_display_name")
)
// ValidateDisplayName ...
func ValidateDisplayName(name string) error {
if len(strings.TrimSpace(name)) == 0 {
return ErrEmailFormat
}
return nil
}
|
package standings
import (
"errors"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/yhat/scrape"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func extractStandingFromNode(row *html.Node, headers []string) Standing {
var standing Standing
teamRegExp := regexp.MustCompile(`^(?:([syxe]) - )?(?:[... |
// Copyright 2017 Xiaomi, 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 in... |
package commands
import (
"flag"
"fmt"
syslog "log"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/eventlog"
"github.com/uhppoted/uhppote-core/uhppote"
"github.com/uhppoted/uhppoted-lib/config"
filelogger "github.com/uhppoted/uhppoted-lib/e... |
package main
import (
"gopkg.in/gomail.v2"
"crypto/tls"
)
func main() {
m := gomail.NewMessage()
m.SetHeader("From", "test@company.com")
m.SetHeader("To", "canux@company.com")
m.SetAddressHeader("Cc", "cheng@company.com", "")
m.SetHeader("Subject", "test subject")
m.SetBody("text/plain", ... |
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
SilenceErrors: true,
SilenceUsage: true,
Use: "ghrls",
Short: "A brief description of your application",
Long: `A longer descr... |
package userlist
import (
"os"
"sync"
"github.com/choria-io/tokens"
)
// User is a choria user
type User struct {
// Username in plain text
Username string `json:"username"`
// Password is a bcrypted password
Password string `json:"password"`
// Organization is a org name the user belongs to
Organization ... |
// Copyright 2022 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 format
import (
"github.com/bazookon/joy4/format/mp4"
"github.com/bazookon/joy4/format/ts"
"github.com/bazookon/joy4/format/rtmp"
"github.com/bazookon/joy4/format/rtsp"
"github.com/bazookon/joy4/format/flv"
"github.com/bazookon/joy4/format/aac"
"github.com/bazookon/joy4/av/avutil"
)
func RegisterAll() ... |
package url
import (
"fmt"
"github.com/gruntwork-io/go-commons/errors"
"net/url"
"strings"
)
// Create a URL with the given base, path parts, query string, and fragment. This method will properly URI encode
// everything and handle leading and trailing slashes.
func FormatUrl(baseUrl string, pathParts []string, q... |
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"os"
"time"
"github.com/brutella/hc"
"github.com/brutella/hc/accessory"
log "github.com/brutella/hc/log"
"github.com/brutella/hc/service"
"github.com/sirupsen/logrus"
"github.com/geoffgarside/homekit-hive/pkg/api/v6/hive"
"github.com/geoffg... |
package client
import (
"fmt"
"strconv"
)
type Config struct {
Protocol string
Host string
Port string
Base string
Token string
}
func DefaultConfig() *Config {
return &Config{Protocol: "http", Host: "10.131.168.227", Port: "3000", Base: "/api/", Token: "7HrftdMvb64WhGIi6pSew40B490bbcyk7kfh4Ks... |
package events
// Event interface that represents the events produced
type Event interface {
Data() []byte // Data of the event
}
// EventSubscriber interface that represents the event listeners
type EventSubscriber interface {
Observe(...string) (<-chan Event, error) // Observe the events
Stop() error ... |
package main
import (
"fmt"
"time"
)
func sum(s []int, c chan int, ms time.Duration) {
sum := 0
for _, v := range s {
sum += v
time.Sleep(ms * time.Millisecond)
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
n2 := len(s)/2
s1 := s[:n2]
s2 := s[n2:]
fmt.Println(s1, s2)
c :... |
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required... |
package 排列组合问题
var permuteSequence [][]int // 结果集
// 返回结果集的函数
func permute(nums []int) [][]int {
/* 1. 进行一些预处理 */
permuteSequence = make([][]int, 0)
/* 2. 调用回溯函数 */
permuteUniqueExec(nums, []int{})
/* 5. 返回结果集 */
return permuteSequence
}
// 回溯函数
func permuteUniqueExec(nums []int, sequence []int) {
/* 3. 判断是... |
package function
func Max(a, b int) int {
if a > b {
return a
}
return b
}
func Maxs(x ...int) int {
if len(x) <= 0 {
return 0
}
ret := x[0]
for _, v := range x {
if ret < v {
ret = v
}
}
return ret
}
func Chmax(a *int, b int) bool {
if *a < b {
*a = b
return true
}
return false
}
|
package resolver_test
import (
"context"
"fmt"
"strconv"
"testing"
gentity "boiler/cmd/server/internal/graphql/entity"
"boiler/cmd/server/internal/graphql/resolver"
"boiler/pkg/entity"
"boiler/pkg/errors"
"boiler/pkg/service/mock"
"boiler/pkg/store"
"github.com/golang/mock/gomock"
"github.com/stretchr/te... |
package pbengine
import (
"bytes"
"log"
"os"
"strings"
"text/template"
"github.com/vanishs/gwsrpc/swg"
)
const tempmain = `package main
import (
"flag"
"{{.Goimportpath}}/gengateway"
)
var (
localaddr = flag.String("addr", ":{{.Localport}}", "http service address")
localssl = flag.String("ssl", "", "ht... |
package goapi
/*
IBootstrapper defines an interface for application to hook bootstrapping routines.
Bootstrapper has access to:
- Application configurations via global variable goapi.AppConfig
- itineris.ApiRouter instance via global variable goapi.ApiRouter
*/
type IBootstrapper interface {
Bootstrap() error
}
|
package service
import (
"encoding/xml"
"fmt"
"net/http"
"github.com/labstack/echo"
)
type User2 struct {
Name string `xml:"name"`
Sex string `xml:"sex"`
}
func GetUser2(c echo.Context) error {
jason := User{Name: "jason", Sex: "male"}
buf, _ := xml.MarshalIndent(jason, "", " ")
fmt.Println(string(buf))
... |
package vocab
// Type represents an ActivityStreams type.
type Type interface {
// GetActivityStreamsId returns the "id" property if it exists, and nil
// otherwise.
GetActivityStreamsId() ActivityStreamsIdProperty
// GetTypeName returns the ActivityStreams type name.
GetTypeName() string
// JSONLDContext return... |
package logger
import (
log "github.com/sirupsen/logrus"
"testing"
"time"
)
func TestConfigLocalFilesystemLogger(t *testing.T) {
ExampleConfigLocalFilesystemLogger()
}
func ExampleConfigLocalFilesystemLogger() {
ConfigLocalFilesystemLogger("D:/projectLog", "log", time.Second*60*3, time.Second*60, log.InfoLevel)... |
package main
import (
"fmt"
"github.com/GeertJohan/go.rice"
"log"
)
func main() {
box, err := rice.FindBox("data")
if err != nil {
log.Fatal(err)
}
s, err := box.String("aes.js")
if err != nil {
log.Fatal(err)
}
fmt.Println(s)
}
|
package main
import (
"encoding/json"
"github.com/hashicorp/memberlist"
)
var (
broadcasts *memberlist.TransmitLimitedQueue
)
// Delegate is the interface that clients must implement if they want to hook
// into the gossip layer of Memberlist. All the methods must be thread-safe,
// as they can and generally will... |
package main
import "fmt"
func two_string() (string, string) {
return "zhong", "ting"
}
func main() {
var name string
n, name := two_string()
fmt.Println(n, name)
}
|
package filter
import (
"camp/week2/controller/user"
"camp/week2/service"
"github.com/simplejia/clog/api"
"net/http"
"time"
)
func Auth(w http.ResponseWriter, r *http.Request, m map[string]interface{}) bool {
fun := "filter auth"
// 获取 cookie 中的 token
tokenCookie, err := r.Cookie("token")
if err != nil {
... |
// tool
package tool
import ()
func Init() {
initRandom()
}
|
package machine
import (
"sync"
)
var routinePool = &pooledRoutines{pool: sync.Pool{New: func() interface{} {
return new(goRoutine)
}}}
var workPool = &pooledWork{pool: sync.Pool{New: func() interface{} {
return &work{
opts: &goOpts{},
fn: nil,
}
}}}
type pooledRoutines struct {
pool sync.Pool
}
func (p... |
package main
import "fmt"
var deckSize int
func main() {
fmt.Println(newCard())
fmt.Println(getMeSomething())
}
func newCard() string {
return "abcd"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.