text stringlengths 11 4.05M |
|---|
/*
Copyright (c) 2018 SAP SE or an SAP affiliate company. 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 app... |
package logger
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
const (
bufferSize = 256 * 1024
)
func getLastCheck(now time.Time) uint64 {
return uint64(now.Year())*1000000 + uint64(now.Month())*10000 + uint64(now.Day())*100 + uint64(now.Hour()... |
package emergencykit
import (
"strings"
"testing"
)
func TestGenerateHTML(t *testing.T) {
out, err := GenerateHTML(&Input{
FirstEncryptedKey: "MyFirstEncryptedKey",
SecondEncryptedKey: "MySecondEncryptedKey",
}, "en")
if err != nil {
t.Fatal(err)
}
if len(out.VerificationCode) != 6 {
t.Fatal("expecte... |
package main
import (
"sync"
"time"
)
//sync.WaitGroup
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1) //最外层等结果的routine来设置累加计数, add一次起一个routine
go func(id int) {
defer wg.Done() //每个routine内部递减计数
time.Sleep(time.Second)
println("goroutine", id, "done")
}(i)
}
println(... |
package fsm
import (
"fmt"
"sort"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/swf"
. "github.com/sclasen/swfsm/log"
. "github.com/sclasen/swfsm/sugar"
)
const (
FilterStatusAll = "ALL" // open + closed
... |
// basic hello world web application just using net/http package
|
package scene
import "time"
// DeltaTime : Delta Time,每次屏幕刷新之间的时间差
type DeltaTime struct {
Last time.Time
Dt float64
}
// NewDT : 生成新的 Delta 实例
func NewDT() DeltaTime {
return DeltaTime{Last: time.Now()}
}
// Update : 刷新并返回Delta Time
func (d *DeltaTime) Update() float64 {
dt := time.Since(d.Last).Seconds()
d... |
package dfm
import "fmt"
type token struct {
tokenType tokenType
text string
// line and col both start at 1.
line, col int
}
// tokenType is a rune because single characters are used directly as their
// token type, e.g. ',' '+' or ':'.
type tokenType rune
const (
tokenIllegal tokenType = -1
tokenEOF... |
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
i := 0
var curr int
var prev int
return func() int {
if i == 0 || i == 1 {
curr = i
i += 1
return i
}
temp := curr
curr += prev
prev = temp
return curr
}
}
func... |
package i18n
const (
SYSTEM_ERROR = "api.system.error"
PARAM_ERROR = "api.context.invalid_body_param.app_error"
MISSING_DATA_ERROR = "api.sql.missing.data"
MISSING_USER_ERROR = "api.sql.missing.user"
MISSING_INVITE_US... |
package service
import (
"context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"geektime/Go-000/Week04/api/user/v1"
"geektime/Go-000/Week04/internal/biz"
"geektime/Go-000/Week04/internal/data"
)
type UserService struct {
v1.UnimplementedUserServer
uc *biz.UserUseCase
}
func New... |
/*
* Copyright 2020-present Open Networking Foundation
*
* 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 applicabl... |
// Change root of a tree
// eg.
// +------0------+
// | | |
// +-1-+ +-2-+ +-3-+
// | | | | | |
// 4 5 6 7 8 9
// re-orientate to:
// 6
// |
// +-----2-----+
// | |
// 7 +-----0-----+
// | |
// +-1-+ +-3-+
// ... |
package cmd
import (
"errors"
"fmt"
"os"
"regexp"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var container string
var (
containers = []string{"dev", "coverage"}
defaultContainer = "dev"
ciBranch = os.Getenv("BUILDKITE_BRANCH")
ciPullRequest = os.Getenv("BUILDKI... |
package sensu
import (
"github.com/bitly/go-simplejson"
)
type Check struct {
Name string `json:"name"`
Command string `json:"command"`
Executed int
Status int
Issued int `json:"issued"`
Output string
Duration float64
Timeout int
commandExe... |
package main
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
"math"
)
var (
maxNonce = math.MaxInt64
maxZero = 2
)
type ProofOfWork struct {
block *Block
}
func (pow *ProofOfWork) Pad() []byte {
src := bytes.Join(
[][]byte{
pow.block.PrevHash,
pow.block.HashTransaction(),
IntToByte(pow... |
package config
const HttpPort = ":80"
const Environment = "env"
const GoogleClientKey = "599717309315-c84f5ijm874mu2of1i1g6qm6ufbfvmn4.apps.googleusercontent.com"
const GoogleSecret = "x9XbDukgssGemHHeni_UBckZ"
const GoogleAuthCallbackUrl = "http://localhost:5000/auth/google/callback?provider=google"
const FacebookCli... |
package pie_test
import (
"github.com/elliotchance/pie/v2"
"github.com/stretchr/testify/assert"
"testing"
)
func TestPop(t *testing.T) {
numbers := []float64{42.0, 4.2}
assert.Equal(t, 42.0, *pie.Pop(&numbers))
assert.Equal(t, []float64{4.2}, numbers)
assert.Equal(t, 4.2, *pie.Pop(&numbers))
assert.Equal(t,... |
package controller
import "github.com/therecipe/qt/core"
var StackController *stackController
type stackController struct {
core.QObject
_ func() `constructor:"init`
_ func(string) `signal:"clicked"`
}
func (c *stackController) init() {
StackController = c
}
|
package service_test
import (
"context"
"crypto/tls"
"net/http"
"strings"
"testing"
authTest "github.com/go-ocf/cloud/authorization/provider"
"github.com/go-ocf/cloud/grpc-gateway/pb"
grpcTest "github.com/go-ocf/cloud/grpc-gateway/test"
"github.com/go-ocf/cloud/http-gateway/test"
"github.com/go-ocf/cloud/ht... |
package authenticate_test
import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"oneday-infrastructure/api/authenticate"
"oneday-infrastructure/internal/pkg/authenticate/domain"
"oneday-infrastructure/tools"
"strings"
"testing"
)
func TestLogin(t *testing.T) ... |
package smtp
import (
"crypto/tls"
"io"
"net/smtp"
)
type smtpClient interface {
Hello(string) error
Extension(string) (bool, string)
StartTLS(*tls.Config) error
Auth(smtp.Auth) error
Mail(string) error
Rcpt(string) error
Data() (io.WriteCloser, error)
Quit() error
Close() error
}
|
package main
import (
"bufio"
"database/sql"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"os"
_ "github.com/mattn/go-sqlite3"
)
// DatabasePath is a constant containig the main sqlite file path
const DatabasePath string = "../persistent/codeImages"
func convertFileToBase64(filePath string) (encoded string, e... |
package slug
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSlug(t *testing.T) {
cases := [][]struct {
in, out string
}{
{
{"foo", "foo"},
{"foo", "foo-1"},
{"foo bar", "foo-bar"},
},
{
{"foo", "foo"},
{"fooCamelCase", "foocamelcase"},
},
{
{"foo", "foo"},
{"... |
package util
import (
"github.com/ActiveState/logyard-apps/common"
"github.com/ActiveState/stackato-go/server"
)
type Config struct {
Info struct {
Name string `json:"name"`
} `json:"info"`
}
var c *server.Config
func getConfig() *Config {
return c.GetConfig().(*Config)
}
func loadConfig() {
var err error
... |
package handler
import (
"fmt"
"github.com/form3tech-oss/jwt-go"
"github.com/gofiber/fiber/v2"
"github.com/serbanmarti/fiber_rest_api/internal"
)
func (h *Handler) Restricted(c *fiber.Ctx) error {
user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(*internal.JWTClaims)
return HTTPSuccess(c, fiber.M... |
package size
import "fmt"
type unit string
const px unit = "px"
const em unit = "em"
const percent unit = "%"
const none unit = "none"
const times unit = "times"
const vw unit = "vw"
const vh unit = "vh"
const vmin unit = "vmin"
const vmax unit = "vmax"
var Auto = Size{unit: none, stringValue: "auto"}
type Size st... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package utils
import (
"fmt"
"net" //nolint:goimports
// #nosec
// register HTTP handler for /debug/pprof
"net/http"
// For pprof
_ "net/http/pprof" // #nosec G108
"os"
"sync"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com... |
package marketplace
import (
"github.com/jinzhu/configor"
"github.com/sonm-io/core/accounts"
)
type MarketplaceConfig struct {
ListenAddr string `yaml:"address"`
Eth accounts.EthConfig `required:"true" yaml:"ethereum"`
}
func NewConfig(path string) (*MarketplaceConfig, error) {
cfg := &Market... |
package vtubers
import (
"context"
"fmt"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
"os"
"time"
)
type (
YoutubeStruct struct {
ChannelId string
Client *youtube.Service
SearchList *youtube.SearchListCall
VideosList *youtube.VideosListCall
ChannelList *youtube.ChannelsL... |
package do_test
import (
"time"
. "github.com/bryanl/dolb/do"
"github.com/bryanl/dolb/mocks"
"github.com/digitalocean/godo"
"github.com/stretchr/testify/mock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var oldActionTimeout time.Duration
var _ = BeforeSuite(func() {
oldActionTimeout = ActionTim... |
package main
import "fmt"
func main() {
s := []int{6,5,9}
fmt.Println(maxProfit(s))
}
func maxProfit(prices []int) int {
n := len(prices)
if n < 2 {
return 0
}
minPrice := prices[0]
maxprofit := 0
for i := 0; i < n; i++ {
if prices[i] < minPrice {
minPrice = prices[i]
} else if prices[i]-minPrice >... |
/*
* Copyright (c) 2020 - present Kurtosis Technologies LLC.
* All Rights Reserved.
*/
package services
const (
MockServicePort = 1000
)
// Mock service, for testing purposes only
type MockService struct {
serviceId ServiceID
ipAddr string
// For testing, the service will report as available on the Nth call... |
package main
import (
"fmt"
"io/ioutil"
"os"
"testing"
)
func sayHi(name string) {
fmt.Printf("hi, %s!\n", name)
}
func Example_sayHi() {
sayHi("winston")
sayHi("sadie")
// Output:
// hi, winston!
// hi, sadie!
}
func Test_sayHi(t *testing.T) {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
... |
package web
import (
"net/http"
"github.com/sirupsen/logrus"
)
type healthChecker struct {
logger logrus.FieldLogger
}
// healthCheck reports if the server is ready to process traffic. It does not validate downstream dependencies.
func (hc *healthChecker) healthCheck(w http.ResponseWriter, req *http.Request) {
... |
package objectstorage
import (
"github.com/go-chi/chi"
"github.com/hardstylez72/bblog/internal/objectstorage"
)
type objectStorageController struct {
objectStorage objectstorage.Storage
}
func NewObjectStorageController(objectStorage objectstorage.Storage) *objectStorageController {
return &objectStorageControll... |
package tude
type Circle struct {
center *Point
radius float64
}
func (c *Circle) Radius() float64 {
return c.radius
}
func (c *Circle) Center() *Point {
return c.center
}
func (c *Circle) Contains(point *Point) bool {
return Distance(point, c.center) <= c.radius
}
func NewCircle(center *Point, radius float64... |
package handlers
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/authentication"
"github.com/authelia/authelia/v4/internal/mocks"
"github.com/authelia/authelia/v4/internal/session"
)
func TestAuthzImplementation(t *testing.T) {
a... |
package router
import "context"
type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
|
package app
import (
"context"
)
// shakespeareKey is a custom string type to ensure no collisions
type shakespeareKey string
func (a *app) GetShakespeareText(ctx context.Context, text string) (string, error) {
key := shakespeareKey(text)
translation, ok := a.shakespeareLRU.Get(key)
if !ok {
var err error
tr... |
package hue
import (
"bytes"
"encoding/json"
"github.com/ermos/hue/internal/logger"
)
func (b *BridgeFetch) Bridge() error {
body, err := b.bridge.get("/config")
if err != nil {
return logger.Error(err)
}
err = json.NewDecoder(bytes.NewBuffer(body)).Decode(&b.bridge.Config)
if err != nil {
return logger.... |
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package rtcp
import (
"testing"
)
func TestPrint(t *testing.T) {
type Tests struct {
packet Packet
expected string
}
tests := []Tests{
{
&ExtendedReport{
SenderSSRC: 0x01020304,
Reports: []Rep... |
package server
import (
"fmt"
"net"
"net/http"
"sync"
"github.com/appootb/substratum/gateway"
"github.com/appootb/substratum/logger"
"github.com/appootb/substratum/rpc"
"github.com/appootb/substratum/util/iphelper"
prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/grpc-ecosystem/grpc-gat... |
package mock
import (
"os"
"testing"
"github.com/10gen/realm-cli/internal/cli/user"
"github.com/10gen/realm-cli/internal/cloud/realm"
u "github.com/10gen/realm-cli/internal/utils/test"
"github.com/10gen/realm-cli/internal/utils/test/assert"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// NewProfile returns... |
package firewall
type ResourceLimiter interface {
Acquire() interface{}
Release(resource interface{})
}
type ChanResourceLimiter struct {
pool chan interface{}
}
// NewChanResourcePool ...
func NewChanResourcePool(cap int) *ChanResourceLimiter {
obj := &ChanResourceLimiter{pool: make(chan interface{}, cap)}
ret... |
package main
import "testing"
var (
sa = StringArray{0, 10, []string{}}
)
func init() {
sa.NewStringArray(&StringArray{})
}
func TestAdd(t *testing.T) {
allCourses := []string{
"CST8101",
"CST8110",
"CST8215",
"CST8300",
"MAT8001",
"empty",
}
for _, course := range allCourses {
sa.Add(course)
}... |
package swift
import (
"fmt"
"io"
"github.com/ncw/swift"
"github.com/root-gg/utils"
"github.com/root-gg/plik/server/common"
"github.com/root-gg/plik/server/data"
)
// Ensure Swift Data Backend implements data.Backend interface
var _ data.Backend = (*Backend)(nil)
// Config describes configuration for Swift d... |
package targets
import (
"os"
"../effects"
)
import . "../defs"
const (
SYNTAX_WLA_DX = 0
SYNTAX_GAS_68K = 1
)
type ICodeGenerator interface {
OutputCallbacks(outFile *os.File) int
OutputChannelData(outFile *os.File) int
OutputEffectFlags(outFile *os.File)
OutputPatte... |
package resources
func checkConnection() {
if connection == nil {
panic("Connection is not initialized in resouces package")
}
}
|
package initDemo
import (
"github.com/cyrilpanicker/golang-snippets/testPackages/package1"
_ "github.com/cyrilpanicker/golang-snippets/testPackages/package2"
)
func Run(){
package1.Package1Function()
}
|
package user_characters
import (
"Golang-API-Game/pkg/repository"
"database/sql"
"log"
)
//UserCharacter table data
type UserCharacter struct {
UserID string
UserCharacterID string
CharacterID string
}
type User struct {
UserID string
Result string
}
type Character struct {
name string
}
//In... |
package main
import (
"io"
"os"
"time"
log "github.com/sirupsen/logrus"
"github.com/webee/multisocket/address"
"github.com/webee/multisocket/examples"
"github.com/webee/multisocket/protocol/stream"
_ "github.com/webee/multisocket/transport/all"
)
func init() {
log.SetLevel(log.DebugLevel)
log.SetFormatter(... |
package main
import (
"fmt"
"strings"
)
func main() {
a := "gopher"
b := "hello world"
//Compare 函數用於比較兩字符串大小
fmt.Println(strings.Compare(a,b)) //a<b output -1
fmt.Println(strings.Compare(a,a)) //a=a output 0
fmt.Println(strings.Compare(b,a)) //b>a output 1
//Join用於連接2字串
var s []string
s = append(s, a, b)... |
package main
import (
"runtime"
"time"
log "github.com/ianwoolf/go-logger/new"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
logger := log.LogDir{
Dir: "./log",
FlushInterval: 2, //s
BufferSize: 256, // k
}
log.SetFall(true) // print all level to info
log.SetConsole(true)
logger... |
package sgs
import (
"er"
"sutil"
)
type appConf struct {
Profile string
DefaultClients int
MinimalClients int
OptimalWaitSecond int
}
//conf sgs web server configuration
type conf struct {
Port int
WSReadBuff int
WSWriteBuff int
BaseTickMs int
AuthSrvURI string
TestEnabled bool... |
package etcd
import (
"context"
"encoding/json"
"fmt"
"github.com/hpcloud/tail"
clientv3 "go.etcd.io/etcd/client/v3"
"log_agent/agent"
"log_agent/config"
"time"
)
type LogType struct {
Topic string `json:"topic"`
Filename string `json:"filename"`
}
func Watch(key string) (err error) {
var cli *clientv3.C... |
package main
import (
"MovieDatabase/handlers"
"MovieDatabase/repo"
"MovieDatabase/service"
"log"
"net/http"
"path/filepath"
)
func main() {
file := "moviedb.json"
ext := filepath.Ext(file)
if ext != ".json" {
log.Fatal("Invalid File Extension")
}
repository := repo.NewRepo(file)
serv := service.Creat... |
package sol
import "testing"
func TestSlice(t *testing.T) {
t.Log(isMatch("mississippi", "mis*is*p*."))
}
|
package modals
import (
"net/http"
"encoding/json"
"strconv"
"github.com/gorilla/mux"
)
// Types
// Events
type Event struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Date string `json:"date,omitempty"`
Time str... |
package items
type Season struct {
ID int64
MovieID int
Number string
}
|
package model
import (
"encoding/json"
)
type Photo struct {
id int64
gallery int64
data []byte
description string
mimetype string
}
type PhotoJSON struct {
Id int64
Gallery int64
Description string
Mimetype string
}
func (p *Photo)MarshalJSON() ([]byte, error){
return json.Marshal(PhotoJSON{
p.id,
p... |
package main
import "fmt"
func main() {
x := 0
// an anonymous function assigned to a variable (func expression)
increment := func() int {
x++
return x
}
fmt.Println(increment())
fmt.Println(increment())
}
/*
Closure helps us limit the scope of variables used by multiple functions
without closure, for two ... |
package beverage
import (
"fmt"
"strings"
)
// Mocha is a decorator. Implements Beverage interface for Mirroring.
type Mocha struct {
baseCost Dollar
description string
beverage Beverage
}
func (m *Mocha) Description() string {
if !strings.Contains(m.beverage.Description(), m.description){
return fmt.S... |
func plusOne(head *ListNode) *ListNode {
dummy := &ListNode{0, head}
process(dummy)
if dummy.Val == 1{
return dummy
} else {
return dummy.Next
}
}
func process(nd *ListNode) int {
var carry, val int
if nd.Next == nil{
carry, val = 0, nd.Val + 1
} else {
c... |
package model
import (
"github.com/jinzhu/gorm"
"wechatvoice/tool/db"
)
type Category struct {
gorm.Model
Uuid string `sql:"size:32;not null"` //主键
CategoryName string //分类名称
}
func init() {
info := new(Category)
info.GetConn().AutoMigrate(&Category{})
}
func (this *Category) GetConn() *gorm.DB {
db... |
package main
/*
* @lc app=leetcode id=47 lang=golang
*
* [47] Permutations II
*/
/*
这道题花了我一整天Debug,最后在StackOverflow上解决了问题
具体请看: https://stackoverflow.com/questions/56649138
*/
// Solution 2: 交换法
func permuteUnique_1(nums []int) [][]int {
qsort_47(nums, 0, len(nums)-1)
res := make([][]int, 0, len(nums))
helper... |
func judgeCircle(moves string) bool {
if len(moves)%2!=0{
return false
}
if strings.Count(moves,"U") != strings.Count(moves,"D"){
return false
}
if strings.Count(moves,"L") != strings.Count(moves,"R"){
return false
}
return true
}
|
package inspect
import (
"fmt"
"sort"
"github.com/square/p2/pkg/health"
"github.com/square/p2/pkg/launch"
"github.com/square/p2/pkg/store/consul"
"github.com/square/p2/pkg/types"
)
const (
INTENT_SOURCE = iota
REALITY_SOURCE
)
type LaunchableVersion struct {
Location string `json:"locatio... |
/*
* @Description:
* @Author: JiaYe
* @Date: 2021-04-09 17:47:13
* @LastEditTime: 2021-04-12 10:01:04
* @LastEditors: JiaYe
*/
package main
import "fmt"
func main() {
//fmt.Println(calc(10, 5))
//sayHello()
//sayHello1("JiaYe")
fmt.Println(add(1, 2))
}
func calc(n1, n2 int) (int, int, int... |
/*
Copyright 2018 Intel Corporation.
SPDX-License-Identifier: Apache-2.0
*/
package oimcommon
import (
"os"
"os/exec"
)
// CmdMonitor can be used to detect when a command terminates
// unexpectedly. It works by letting the command inherit the write
// end of a pipe, then closing that end in the parent process and... |
package webcam
import (
"bytes"
"encoding/binary"
"unsafe"
"github.com/stanier/webcam/ioctl"
"golang.org/x/sys/unix"
)
const (
V4L2_CAP_VIDEO_CAPTURE uint32 = 0x00000001
V4L2_CAP_STREAMING uint32 = 0x04000000
V4L2_BUF_TYPE_VIDEO_CAPTURE uint32 = 1
V4L2_MEMORY_MMAP uint32 = 1
V4L2_F... |
package main
import "fmt"
func main() {
f := 7 / 0.5
fmt.Println(f)
f2 := 20 / 30.0
fmt.Println(f2)
f = 7 / f2
fmt.Println(f)
}
/**
最低票价
在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。
火车票有三种不同的销售方式:
- 一张为期一天的通行证售价为 costs[0] 美元;
- 一张为期七天的通行证售价为 costs[1] 美元;
- 一张为期三十天的通... |
package codegen
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
shellquote "github.com/kballard/go-shellquote"
"github.com/moby/buildkit/client"
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/identity"
"github.com/moby/buildkit/session/... |
package neo_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/yggie/github-data-challenge-2014/models"
"github.com/yggie/github-data-challenge-2014/neo"
)
var _ = Describe("Persist", func() {
neo.Clear(neo.ALL)
var err error
Context("PersistPushEvent", func() {
var pushEvent mo... |
package main
import (
"context"
"os"
"github.com/rodrigo-brito/ninjabot"
"github.com/rodrigo-brito/ninjabot/example"
"github.com/rodrigo-brito/ninjabot/pkg/exchange"
"github.com/rodrigo-brito/ninjabot/pkg/model"
"github.com/rodrigo-brito/ninjabot/pkg/notification"
"github.com/rodrigo-brito/ninjabot/pkg/storag... |
package event
import (
"subd/models"
"time"
)
type Repository interface {
CheckUser(user string) (bool, error)
CheckUserByEmail(email string) (bool, error)
CheckUserByNicknameOrEmail(nickname string, email string) (bool, error)
AddNewForum(newForum *models.Forum) (error, bool)
GetForumCounts(slug string) (uint... |
/*
Copyright 2021 The KubeVela 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, softw... |
package apiauth
import (
"bytes"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
//Finder is a method which takes clients accessID and the request as input and
// returns secretKey of the associated accessID.
// It also allows you t... |
package lcd
import (
"net/http"
"github.com/gorilla/mux"
"github.com/irisnet/irishub/client/context"
"github.com/irisnet/irishub/codec"
)
func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) {
// Get rand by the request id
r.HandleFunc(
"/rand/rands/{request-id}",
queryRandH... |
package redcode
import (
"testing"
"github.com/go-test/deep"
)
func TestSanity(t *testing.T) {
checkInstructions(t, " MOV #7, -1\n", Instruction{
Opcode: OpMov,
A: Operand{Mode: Immediate, Expression: constNum(7)},
B: Operand{Mode: Relative, Expression: constNum(-1)},
})
checkInstructions(t, "m... |
package main
import (
"fmt"
)
func main() {
re := twoSum([]int{3, 3, 4}, 6)
fmt.Println(re)
}
func twoSum(nums []int, target int) []int {
m := make(map[int]int, len(nums))
for k, v := range nums {
if _, ok := m[v]; ok {
return []int{m[v], k}
}
m[target-v] = k
}
return nil
}
|
package main
import "fmt"
func main() {
fmt.Println(countCompleteComponents(3, [][]int{
{1, 0},
{2, 1},
}))
fmt.Println(countCompleteComponents(6, [][]int{
{0, 1},
{0, 2},
{1, 2},
{3, 4},
}))
}
func countCompleteComponents(n int, edges [][]int) int {
grid := make([][]int, n)
for i := range grid {
... |
package env
// Package Constants
const (
// Eventing-Kafka Configuration
ServiceAccountEnvVarKey = "SERVICE_ACCOUNT"
MetricsPortEnvVarKey = "METRICS_PORT"
HealthPortEnvVarKey = "HEALTH_PORT"
// Kafka Authorization
KafkaBrokerEnvVarKey = "KAFKA_BROKERS"
KafkaUsernameEnvVarKey = "KAFKA_USERNAME"
KafkaP... |
package domain
import "time"
// Asset is the Asset information from Nexpose
type Asset struct {
ScanTime time.Time
ID int64
IP string
Hostname string
}
|
package pgsql
import (
"testing"
"time"
)
func TestTimetz(t *testing.T) {
dublin, err := time.LoadLocation("Europe/Dublin")
if err != nil {
t.Fatal(err)
}
testlist2{{
data: []testdata{
{
input: timetzval(21, 5, 33, 0, dublin),
output: timetzval(21, 5, 33, 0, dublin)},
{
input: timetzval... |
// Copyright 2016 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 main
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/golang/dep"
"github.com/golang/dep/gps"
"github.com/golang/dep/gps/paths... |
package purchaseorder
import (
"github.com/centrifuge/centrifuge-protobufs/gen/go/purchaseorder"
"github.com/centrifuge/go-centrifuge/documents"
clientpb "github.com/centrifuge/go-centrifuge/protobufs/gen/go/purchaseorder"
"github.com/centrifuge/go-centrifuge/utils/timeutils"
)
func toClientLineItems(items []*Lin... |
package helper
import (
"neosmemo/backend/util"
"net/http"
"time"
)
// Session session type
type Session struct {
UserID string
SessionID string
CreatedAt time.Time
ExpiredAt time.Time
}
// SessionManager SessionID-Session.UserID
//
// Session Manager Design Purpose:
// 1. 用加密的 session text 取代 user_id
// 2... |
package main
/*
* @lc app=leetcode id=543 lang=golang
*
* [543] Diameter of Binary Tree
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var best int
func diameterOfBinaryTree(root *TreeNode) int {
best = 0
getDepth(root)... |
/*
The Recamán Sequence is a numeric sequence that starts always with 0. The position of a positive integer in the sequence, or Recamán Index, can be established with the following algorithm:
For every number to find, two variables are considered: the value of the last element of the sequence (last element from n... |
package routes
import (
//"github.com/adamveld12/goadventure/game"
// "fmt"
// "github.com/adamveld12/goadventure/persistence"
// "github.com/adamveld12/sessionauth"
"github.com/go-martini/martini"
// "github.com/martini-contrib/render"
// "github.com/martini-contrib/sessions"
// "log"
// "net/http"
)
func r... |
package mux
import (
"encoding/json"
"errors"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
"strconv"
)
func RouterStart() {
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
// 根据不同的id返回不同的文章对象
router.Path("/article/{id:[0-9]+}").HandlerFunc(ArticleHandler)
// sub router
s := router.Host(d... |
package utils
import (
"log"
"os"
)
func DirExists(name string) bool {
info, err := os.Stat(name)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
func SliceToSet(slice []string) map[string]bool {
result := make(map[string]bool)
for _, x := range slice {
if _, ok := result[x]; ok {
log.Fat... |
package main
import (
"bufio"
"fmt"
"log"
"io"
"os"
"strings"
"strconv"
)
const (
ascii_offset byte = 97
ascii_int_offset
)
func checkErr(err error) {
if err != nil {
log.Fatalf("Error: %v", err)
}
}
func getIndex(set []byte, match byte) int {
for i, b := range set {
if b ... |
package drobox
import (
"encoding/json"
"fmt"
"reflect"
"testing"
"time"
)
func TestDocIdListParse(t *testing.T) {
jsonString := `{
"doc_ids": [
"aaaaaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbbbbbbbbb"
],
"cursor": {
"value": "value_sample",
"expiration": "2000-01-01T09:00:00Z"
},
"has_more": fal... |
package cmd
import (
"github.com/spf13/cobra"
)
var (
skipKeyring bool
)
var configureCmd = &cobra.Command{
Use: "configure",
Short: "Configure a connection to a running server and locally persist credentials for later use",
Long: `
Launch an interactive process to configure a connection to a running Pydio Ce... |
package transport
import (
"context"
"encoding/json"
"fmt"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/tracing/zipkin"
httptransport "github.com/go-kit/kit/transport/http"
"github.com/gorilla/mux"
"github.com/mashenjun/courier/com"
"github.com/mashenjun/courier/pkg/endpoint"
"github.com/mashenjun/cour... |
package main
/*
给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,
其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。
*/
// 计算平面中相同距离点的对数 (排列数,不是组合)
func numberOfBoomerangs(points [][]int) int {
ans := 0
for i := 0; i < len(points); i++ {
sameDistancePointCount := make(map[int]int)
for t := 0; t < len(points); t++ {
di... |
package csv
import (
"encoding/csv"
"fmt"
"os"
"strconv"
"time"
)
type ethCsv struct {
Date string `json:"date"`
Amount float64 `json:"amount"`
}
func PricesEth(sdate string) (prices []*ethCsv, err error) {
dt_start := uxdate(sdate)
csvFile, err := os.Open("./static/csv/eth.csv")
if err != nil {
retur... |
package core
import "context"
type Request interface{}
type RequestHandler func(
ctx context.Context,
request interface{}) Result
type Notification interface{}
type NotificationHandler func(
ctx context.Context,
notification interface{}) error
type ReplyHandler func(receivedData interface{})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.