text stringlengths 11 4.05M |
|---|
package secrets
import (
"errors"
"strings"
"testing"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/utils/test/assert"
"github.com/10gen/realm-cli/internal/utils/test/mock"
)
func TestSecretsListHandler(t *testing.T) {
project... |
// Copyright 2021 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 atomix
import (
"strconv"
"sync/atomic"
)
// Bool is an atomic boolean.
type Bool struct {
atomicType
value uint32
}
// NewBool creates a Bool.
func NewBool(value bool) *Bool {
return &Bool{value: b2i(value)}
}
func (b *Bool) String() string {
return strconv.FormatBool(b.Load())
}
// Load atomically ... |
package leetcode
import "testing"
func TestRecentCounter(t *testing.T) {
obj := Constructor()
inputs := []int{1, 100, 3001, 3002}
expected := []int{1, 2, 3, 3}
for i := 0; i < 4; i++ {
if obj.Ping(inputs[i]) != expected[i] {
t.Fatal()
}
}
}
|
package main
import (
"fmt"
"net/http"
"strings"
)
func main() {
//general testing
test := sendRequest("player", "", "43db704e10b140b3a38dce059de35a59")
fmt.Println(test.Body)
}
func sendRequest(apiType string, apiKey string, uuid string) *http.Response {
apiUrl := "https://api.hypixel.net/" + apiKey + "?ke... |
package cache
import (
"log"
"time"
"github.com/dgraph-io/badger"
)
type BadgerDBCache struct {
db *badger.DB
}
func (b *BadgerDBCache) Set(k []byte, v []byte) error {
err := b.db.Update(func(txn *badger.Txn) error {
return txn.Set(k, v)
})
return err
}
func (b *BadgerDBCache) Setex(k []byte, ttl time.Dur... |
// Assembly symbol map.
package main
import (
"fmt"
"reflect"
"sort"
"strings"
)
type Symbol struct {
Constant bool // Constness of the stored value.
Val asmVal
}
func (s Symbol) String() string {
var ret string
if s.Constant {
ret = "(const) "
}
return ret + s.Val.String() + "... |
package queue_test
import (
"bytes"
"github.com/hx/queue"
"reflect"
"sync"
"testing"
"time"
)
func Assert(tb testing.TB, cond bool, msg string, v ...interface{}) {
tb.Helper()
if !cond {
tb.Logf(msg, v...)
tb.FailNow()
}
}
func Equal(tb testing.TB, exp interface{}, act interface{}) {
tb.Helper()
Asser... |
package handlers
import (
"fmt"
"net/url"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/model"
"github.com/authelia/authelia/v4/internal/session"
)
func getWebAuthnUser(ctx... |
package hasedbuffer
import (
"bytes"
"encoding/hex"
"github.com/AppImageCrafters/libzsync-go/rollinghash"
"github.com/glycerine/rbuf"
"golang.org/x/crypto/md4"
"io"
)
type HashedRingBuffer struct {
hash *rollinghash.RollingHash
rBuf *rbuf.FixedSizeRingBuf
}
func NewHashedBuffer(size int) *HashedRingBuffer {
... |
package storage
import (
"context"
"database/sql"
"time"
"github.com/google/uuid"
"github.com/ory/fosite/storage"
"github.com/authelia/authelia/v4/internal/model"
)
// Provider is an interface providing storage capabilities for persisting any kind of data related to Authelia.
type Provider interface {
model.... |
/*
Copyright IBM Corporation 2020
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 handlers contains the full set of handler functions and routes
// supported by the web api.
package handlers
import (
"log"
"net/http"
"os"
"github.com/dimfeld/httptreemux"
)
// API constructs an http.Handler with all application routes defined.
func API(build string, shutdown chan os.Signal, log *log... |
package payment
import (
"errors"
"fmt"
"regexp"
"time"
)
// CreditAccount ...
type CreditAccount struct {
Account
ownerName string
cardNumber string
expirationMonth int
expirationYear int
securityCode int
availableCredit int
}
var cardNumberPattern = regexp.MustCompile("^[\\d{4}-]{3}\\d{4}... |
package seev
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01100101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.011.001.01 Document"`
Message *AgentCANotificationStatusAdviceV01 `xml:"AgtCANtfctnStsAdvc"`
}
func ... |
package main
import (
"fmt"
// "learn10/interface_demo"
// "learn10/empty_interface"
"logger"
)
func InitLogger(name, filePath, fileName, level string) {
config := make(map[string]string, 8)
config["log_level"] = level
config["log_path"] = filePath
config["log_name"] = fileName
err := logger.InitLogger(name,... |
/*
* outer: outer product
*
* input:
* vector: a vector of (x, y) points
* nelts: the number of points
*
* output:
* Outer_matrix: a real matrix, whose values are filled with inter-point
* distances
* Outer_vector: a real vector, whose values are filled with origin-to-point
* distances
*/
p... |
package main
type GamePlay struct {
Entities Entities `json:Entities, omitempty`
ResultEntities ResultEntities `json:ResultEntities, omitempty`
TotalCreditPayout int `json:TotalCreditPayout, omitempty`
}
func (status *GamePlay) GetEntities() Entities {
entities := Entities{
Entity{
... |
package main
import "testing"
func TestRemoveHTMLTag(t *testing.T) {
tests := []struct {
input string
want string
}{
{
input: "<div>test</div>",
want: "test",
},
{
input: "<div class='test'>test</div>",
want: "test",
},
{
input: "<div class='test'><!-- test -->test</div>",
want: ... |
package codec
import (
"image"
"github.com/edaniels/golog"
)
// DefaultKeyFrameInterval is the default interval chosen
// in order to produce high enough quality results at a low
// latency.
const DefaultKeyFrameInterval = 30
// An Encoder is anything that can encode images into bytes. This means that
// the enco... |
package main
import (
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/aw... |
package datastruct
import (
"fmt"
)
type Set interface {
Insert(x interface{})
Erase(x interface{})
Contains(x interface{}) bool
Size() int
}
type SetImpl struct {
data map[interface{}]struct{}
}
func NewSet() *SetImpl {
return &SetImpl{data: make(map[interface{}]struct{})}
}
func (s *SetImpl) Insert(x inte... |
// Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package main
import (
"math"
"sync"
"github.com/facebookexperimental/GOAR/endpoints"
"github.com/golang... |
package mutex
import (
"runtime"
"sync/atomic"
)
type Mutex struct {
state int32
}
func (m *Mutex) TryLock() bool {
return atomic.CompareAndSwapInt32(&m.state, 0, 1)
}
func (m *Mutex) Lock() {
for !m.TryLock() {
runtime.Gosched()
}
}
func (m *Mutex) Unlock() {
atomic.StoreInt32(&m.state, 0)
}
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Println("Welcome!\n")
t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.Local)
fmt.Println("Go launched at \n", t.Local(... |
package constant
const (
// APPNAME app name
APPNAME = "QueueMan"
// APPVERSION app version
APPVERSION = "V1.0.9"
)
|
package Crypto
import (
"bytes"
"crypto/cipher"
"crypto/des"
"encoding/hex"
"fmt"
)
func main() {
//key的长度必须都是8位
var key = "12345678"
var info = "asdfgasdfgasdfgasdfgasdfg"
Enc_str := EncryptDES_CBC(info, key)
fmt.Println(Enc_str)
Dec_str := DecryptDES_CBC(Enc_str, key)
fmt.Println(Dec_str)
Enc_str = E... |
package registry
import (
"bytes"
"fmt"
"github.com/iotaledger/wasp/packages/dbprovider"
"io"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/publisher"
"github... |
// +build spi,!i2c
package main
import (
// Modules
_ "github.com/djthorpe/gopi-hw/sys/spi"
_ "github.com/djthorpe/sensors/sys/rfm69"
)
const (
MODULE_NAME = "sensors/rfm69/spi"
)
|
/*
Copyright 2021 CodeNotary, 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.
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 labels
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
. "github.com/anthonybishopric/gotcha"
"github.com/square/p2/pkg/logging"
"k8s.io/kubernetes/pkg/labels"
)
const endpointSuffix = "/api/select"
func getMatches(t *testing.T, httpResponse string) ([]Labeled, erro... |
package cartao_credito
import "fmt"
type Cartao struct {
ID int `json:"id"`
Valor float64 `json:"valor"`
Descricao string `json:"descricao"`
Local string `json:"local"`
Usuario Usuario `json:"usuario"`
}
type Usuario struct {
ID int `json:"id"`
Login string `json:"login"`
Email s... |
package linkedlists
import (
"testing"
)
var kthTests = []struct {
l *ListNode
result *ListNode
k int
}{
{
&ListNode{1, nil},
&ListNode{1, nil},
0,
},
{
&ListNode{1, &ListNode{1, nil}},
&ListNode{1, nil},
1,
},
{
&ListNode{1, &ListNode{1, &ListNode{8, &ListNode{1, nil}}}},
&ListNode... |
package helpers
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
// GetInputValues reads the file at the specified input path, strips the last line (if needed) and returns the content as string array
func GetInputValues(absFilePath string) (values []string) {
txt, err := ioutil.ReadFile("input")
if err != nil {... |
package main
import (
"context"
"fmt"
"os"
slackbot "github.com/lusis/go-slackbot"
slack "github.com/nlopes/slack"
)
func helloFunc(ctx context.Context, bot *slackbot.Bot, evt *slack.MessageEvent) {
bot.Reply(evt, "hi there to you too!", slackbot.WithoutTyping)
}
func globalMessageHandler(ctx context.Context,... |
package base
import (
"sync"
)
type SentinelEntry struct {
res *ResourceWrapper
// one entry with one context
ctx *EntryContext
// each entry holds a slot chain.
// it means this entry will go through the sc
sc *SlotChain
exitCtl sync.Once
}
func NewSentinelEntry(ctx *EntryContext, rw *ResourceWrapper, sc *... |
// Copyright 2016 IBM 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 by applicable law or... |
package tlsconfig
import (
"crypto/tls"
)
func Secure(certificates []tls.Certificate) *tls.Config {
tlsConfig := &tls.Config{
// Causes servers to use Go's default ciphersuite preferences,
// which are tuned to avoid attacks. Does nothing on clients.
PreferServerCipherSuites: true,
// Only use curves which ... |
package fakes
import "github.com/cloudfoundry-incubator/notifications/postal"
type TemplatesLoader struct {
ContentSuffix string
Templates postal.Templates
LoadError error
}
func (fake *TemplatesLoader) LoadTemplates(subjectSuffix, contentSuffix, clientID, kindID string) (postal.Templates, error)... |
// Copyright (c) 2014 Dataence, 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 app... |
package example
type Order struct {
ID string
}
func processRequest() {
// What is this true stand for, why i put true value in here????
o, err := CreateOrder("product id", "customer id", "shipment id", true)
if err != nil {
panic(err)
}
}
func CreateOrder(productID, customerID, shipmentID string, isPromotion... |
package main
import "fmt"
func main() {
fmt.Println(firstMissingPositive([]int{
//1, 2, 0,
//3, 2, 4, -1, 1,
1, 1,
}))
}
func firstMissingPositive(nums []int) int {
for i := 0; i < len(nums); i++ {
for nums[i] != i+1 && nums[i]-1 >= 0 {
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
}
}
for... |
package forum
import (
"time"
"github.com/kapmahc/axe/plugins/nut"
)
// Article article
type Article struct {
tableName struct{} `sql:"forum_articles"`
ID uint `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
Type string `json:"type"`
User nut.User `... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package main
import (
"testing"
"image/color"
"fmt"
)
func TestTransfColor(t *testing.T) {
c := transfColor(color.RGBA{
R: 218,
G: 210,
B: 137,
A: 0xff,
})
fmt.Printf("R:0x%x G:0x%x B:0x%x A:0x%x\n", c.R, c.G, c.B, c.A)
fmt.Printf("R:%d G:%d B:%d A:%d\n", c.R, c.G, c.B, c.A)
}
|
func min(x int, y int) int {
if x > y {
return y
}
return x
}
func minDepth(root *TreeNode) int {
if root == nil {
return 0
} else {
var l = minDepth(root.Left)
var r = minDepth(root.Right)
if l == 0 {
return r + 1
}
if r == 0 {
return l + 1
}
return min(l, r) + 1
}
} |
package utils
import (
"github.com/go-ini/ini"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func Test_Config(t *testing.T) {
Convey("Test Set", t, func() {
Convey("initest", func() {
k := &Config{" ", "/tmp/ts.ini"} //note:you can set ts.ini 's location
k.SaveDefaultUnpackerArgs(40*1024, 21)
... |
package storage
import (
"testing"
"github.com/magiconair/properties/assert"
)
func TestGetFile(t *testing.T) {
for _, tc := range getFileTestCases {
t.Run(tc.name, func(t *testing.T) {
output := tc.s3.GetFile(tc.cid)
assert.Equal(t, output, tc.result)
})
}
}
type getFileData struct {
name string
... |
package main
import (
"fmt"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/holly-graham/scheduleapi/db"
"github.com/holly-graham/scheduleapi/schedule"
"github.com/holly-graham/scheduleapi/server"
)
const port = ":8000"
func main() {
db, err := db.ConnectDatabase("ac... |
// Package server provides HTTP/2 gRCP server functionality.
package server
|
package database
import (
"github.com/jinzhu/gorm"
)
type Mysql struct {
db *gorm.DB
}
func (mysql Mysql) New() *gorm.DB{
db, _ := gorm.Open("mysql", "root:@/learnsong?charset=utf8&parseTime=True&loc=Local")
mysql.db = db
return mysql.db
}
|
package ewallet_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xendit/xendit-go/ewallet"
v1 "github.com/imrenagi/go-payment/gateway/xendit/ewallet/v1"
"github.com/imrenagi/go-payment/invoice"
)
func TestNewOvo(t *testing.T) {
tests := []struct {
name string
inv... |
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
... |
package git
import (
"errors"
"testing"
"github.com/abhinav/git-pr/gateway"
"github.com/abhinav/git-pr/gateway/gatewaytest"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBulkRebaser(t *testing.T) {
type deletion struct {
Checkout stri... |
package delete
import (
"fmt"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/pkg/iostreams"
"github.com/heaths/gh-label/internal/github"
"github.com/heaths/gh-label/internal/options"
"github.com/spf13/cobra"
)
type deleteOptions struct {
name string
// test
client *github.Client
io *iostreams.IO... |
package config
import (
"fmt"
"github.com/BurntSushi/toml"
"github.com/pkg/errors"
)
// Настройки микросервиса
type Options struct {
HTTPServer HTTPServer
}
// Инициализация конфигов
func Init(configPath string) (options *Options, err error) {
if _, err = toml.DecodeFile(configPath, &options); err != nil {
re... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2019-05-04 08:49
# @File : validation.go
# @Description :
*/
package utils
import (
"math/rand"
"regexp"
"strconv"
"time"
)
// FIXME
// 手机号校验
func ValidatePhone(phone string) bool {
// 手机号
regExp := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0... |
// Copyright 2017 Łukasz Pankowski <lukpank at o2 dot pl>. All rights
// reserved. This source code is licensed under the terms of the MIT
// license. See LICENSE file for details.
package jsonlexer_test
import (
"bytes"
"fmt"
"io"
"strings"
"testing"
"github.com/lukpank/jsonlexer"
)
func TestLexerEmptyArray... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
const df = "downloaded"
func download(i int) {
fn := fmt.Sprintf("index%d.html", i)
resp, _ := http.Get("https://www.ptt.cc/bbs/movie/" + fn)
body, _ := ioutil.ReadAll(resp.Body)
ioutil.WriteFile(df+"/"+fn, body, 0644)
}
func main() {
// 創建下載後放檔案的目錄... |
package filelist
import (
"bytes"
"errors"
)
var (
errInvalidEscape = errors.New("invalid escape sequence")
)
func hexToInt(in byte) uint8 {
switch {
case '0' <= in && in <= '9':
return in - '0'
case 'a' <= in && in <= 'f':
return in - 'a' + 10
case 'A' <= in && in <= 'F':
return in - 'A' + 10
}
retur... |
package coupons
import (
"context"
"database/sql"
"time"
"cinemo.com/shoping-cart/internal/discounts"
"cinemo.com/shoping-cart/internal/products"
)
// Service is the interface to expose coupons functions
type Service interface {
CreateCoupon(ctx context.Context, now time.Time) (*Coupon, error)
RetrieveCouponP... |
package client
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/Azure/go-autorest/autorest/to"
"github.com/pkg/errors"
az "github.com/ydye/personal-az-sdk-practise/pkg/azure"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/apimanagement/mg... |
// primo2.go
// verifica se um número é primo
// arataca89@gmail.com
// 20210413
package main
import "fmt"
func isprime(nr int) bool {
for divisor := 2; divisor < nr; divisor++ {
if nr%divisor == 0 {
return false
}
}
return true
}
func main() {
var nr int
fmt.Print("Entre com o... |
package rpcd
import (
"github.com/Cloud-Foundations/Dominator/lib/errors"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
"github.com/Cloud-Foundations/Dominator/proto/hypervisor"
)
func (t *srpcType) ChangeVmVolumeSize(conn *srpc.Conn,
request hypervisor.ChangeVmVolumeSizeRequest,
reply *hypervisor.ChangeVmVo... |
package main
type ColorStringer interface {
ColorString() string
}
|
package logs
import (
"fmt"
"os"
)
// NewStdLogger creats new std out logger
func NewStdLogger() *StdLogger {
var stdlogger StdLogger
file, err := os.OpenFile("/dev/stdout", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
fmt.Println(err)
}
stdlogger.fd = file
return &stdlogger
}
// Println func... |
package main
import (
"balansir/internal/configutil"
"balansir/internal/limitutil"
"balansir/internal/listenutil"
"balansir/internal/logutil"
"balansir/internal/poolutil"
"balansir/internal/rateutil"
"balansir/internal/watchutil"
"fmt"
"io/ioutil"
"os"
)
func main() {
logutil.Init()
logutil.Info("Booting ... |
package elasticrecipes
import (
"context"
"io/ioutil"
"log"
elastic "github.com/olivere/elastic"
)
// Create Index and config trough mapjsonfile
func SetMap(client *elastic.Client, index string, mapjsonfile string) (created bool, e error) {
var err error
var indexcreated bool
log.Println("setting ", mapjsonf... |
package neo
import "github.com/jmcvetta/neoism"
func Count(modelType _Type) int {
var statement string
var result interface{}
if modelType == ALL {
statement = `MATCH (n) RETURN count(n) as count`
} else {
statement = `MATCH (:` + string(modelType) + `) RETURN count(*) as count`
}
query := neoism.CypherQu... |
package network
type IServer interface {
Listen(packet IPacket, startPort int, endPort int, isAllowConnFunc func(conn interface{}) bool) int
Close()
}
|
package parameters
import (
"github.com/iotaledger/wasp/plugins/config"
flag "github.com/spf13/pflag"
)
const (
LoggerLevel = "logger.level"
LoggerDisableCaller = "logger.disableCaller"
LoggerDisableStacktrace = "logger.disableStacktrace"
LoggerEncoding = "logger.encoding"
LoggerOutput... |
package controller
import (
"encoding/json"
"math/rand"
"strings"
"sync"
"time"
"github.com/reechou/holmes"
"github.com/reechou/robot-manager/config"
"github.com/reechou/robot-manager/models"
)
const (
GROUP_MASS_TYPE_ALL = 1
GROUP_MASS_TYPE_SELECT_GROUPS = 2
GROUP_MASS_WORKER = 1024... |
package fateRPGtest
import (
"testing"
"github.com/faterpg"
)
// Lily’s character, Cynere, has the
// aspect Tempted by Shiny Things
// on her sheet, which describes her
// general tendency to overvalue
// material goods and make bad
// decisions when gems and coin are
// involved. This adds an interesting,
// fun... |
package realm
// set of supported data source types
const (
ServiceTypeCluster = "mongodb-atlas"
ServiceTypeDatalake = "datalake"
)
// default names for data source types
const (
DefaultServiceNameCluster = "mongodb-atlas"
)
|
package main
import "fmt"
import "io/ioutil"
import "regexp"
import "flag"
var re = regexp.MustCompile(".w.$")
func readDirectory(dir string, depth int) []string {
// fmt.Printf("%s with depth %d\n", dir, depth)
if depth < 0 {
return []string{}
}
files, err := ioutil.ReadDir(dir)
if err != nil {
//fmt.Prin... |
package login
import (
"encoding/json"
"fmt"
"net/http"
"github.com/Tedyst/gotest/util"
)
//Handler stfu
func Handler(w http.ResponseWriter, r *http.Request) {
jwt, err := Authenticate(r)
if jwt != "" {
fmt.Fprintf(w, jwt)
return
}
if err != nil {
asd := err.(*util.ErrorString)
str, _ := util.ErrorJS... |
package hot100
// 关键
// 无他: 死记硬背
// 1. for 循环, 右移缩小index位
// 2. 异或^ 缩小的值即可
func grayCode(n int) []int {
ret := make([]int, 1<<n)
for index := range ret {
ret[index] = index>>1 ^ index
}
return ret
}
|
package smallNet
type ringBuffer struct {
_data []byte
_allocSize int // data의 실제 할당 크기
_maxSize int // data의 최대 크기
_maxPacketSize int
_writeCursor int
_readCursor int
}
// 링버퍼를 한바퀴 돌 때 앞에 데이터를 다 사용했는지 체크 하지 않는다. 즉 낙관적이다
// 그래서 버퍼의 크기(maxSize)는 꽤 넉넉해야 한다.
func newRingBuffer(maxSize int, maxPack... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"os/exec"
"strings"
"time"
"github.com/fatih/color"
"github.com/pkg/errors"
)
var (
SEPARATOR = []byte("<<SEP")
)
type Change struct {
Name string
File string
Details []string
}
type CommitDetails struct {
Author string
Commit string
Date t... |
package main
import "fmt"
type cliente struct {
nome string
sobrenome string
fumante bool
}
func main() {
c1 := cliente{
nome: "João",
sobrenome: "da Silva",
fumante: false,
}
c2 := cliente{"Joana", "Pereira", true}
fmt.Println(c1)
fmt.Println(c2)
}
|
package main
import (
"flag"
"fmt"
"goChat/Server/db"
"goChat/Server/inMemoryDatabase"
"goChat/Server/mongo"
"goChat/Server/services"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
port := flag.Int("port", 5020, "Port number for the server to use")
inMemoryDb := flag... |
package ttlib
import (
"github.com/johnnylee/util"
)
// ClientConfig: A configuration file for a client.
type ClientConfig struct {
Host string // The host address: <address>:<port>.
User string // The username for the client.
Pwd []byte // The user's password.
CaCert []byte // The CA certificate.
}
// L... |
package kafkaflow
import "github.com/trustmaster/goflow"
// NewUpperApp wires together the compoents
func NewUpperApp() *goflow.Graph {
u := goflow.NewGraph()
u.Add("upper", new(Upper))
u.Add("printer", new(Printer))
u.Connect("upper", "Res", "printer", "Line")
u.MapInPort("In", "upper", "Val")
return u
}
|
/*
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.
Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N.
When someone connects to... |
package main
import "github.com/bbrowning/ocf/cmd"
func main() {
cmd.Execute()
}
|
// Copyright 2019 Amazon.com, Inc. or its affiliates. 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 at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license"... |
package leetcode
import (
"reflect"
"testing"
)
func TestRemoveElement(t *testing.T) {
tests := []struct {
nums []int
val int
results []int
}{
{
nums: []int{},
val: 0,
results: []int{},
},
{
nums: []int{1},
val: 1,
results: []int{},
},
{
nums: []int{1, ... |
package databroker
import (
"context"
"fmt"
"io"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/registry"
"github.com/pomerium/pomerium/internal/registry/inmemory"
"github.com/pomerium/pomerium/internal/registry/redis"
"github.com/pome... |
package pgsql
import (
"testing"
)
func TestInt2VectorArray(t *testing.T) {
testlist2{{
valuer: Int2VectorArrayFromIntSliceSlice,
scanner: Int2VectorArrayToIntSliceSlice,
data: []testdata{
{
input: [][]int{{-32768, 32767}, {0, 1, 2, 3}},
output: [][]int{{-32768, 32767}, {0, 1, 2, 3}}},
},
}, {... |
/*
* @lc app=leetcode.cn id=236 lang=golang
*
* [236] 二叉树的最近公共祖先
*/
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// @lc code=start
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := l... |
package devicesearch
import (
"github.com/rakyll/portmidi"
"github.com/telyn/midi"
"github.com/telyn/midi/portbidi"
"github.com/telyn/midi/stream"
)
type SearchResult struct {
In *portmidi.Stream
Out *portmidi.Stream
Stream stream.Stream
Channel byte
}
func (res SearchResult) Processor(dispatch mid... |
// Copyright © 2020 Attestant Limited.
// Licensed )junder 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 main
import (
"github.com/gin-gonic/gin"
"gitlab.com/pragmaticreviews/golang-gin-poc/service"
"gitlab.com/pragmaticreviews/golang-gin-poc/controller"
)
var(
videoService service.VideoService =service.New()
videoController controller.VideoController =controller.New(videoService)
)
func main(){
server := gin.... |
package goticker
import (
"sync"
"time"
)
type Ticker struct {
fn func(arg interface{})
ch chan bool
wg sync.WaitGroup
interval int
}
func New(interval int, fn func(arg interface{})) *Ticker {
return &Ticker{
fn: fn,
ch: make(chan bool, 1),
interval: interval,
}
}
func (t... |
package issue
import (
"fmt"
"time"
"williamfeng323/mooncake-duty/src/domains/project"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"williamfeng323/mooncake-duty/src/infrastructure/db"
repoimpl "williamfeng323/mooncake-duty/src/infrastructure/db/repo_impl"
validatorimpl "wi... |
package main
func (this *Application) ProjectIssueCreateAction(args []string) {
}
|
package dynamo
import (
"github.com/aws/aws-sdk-go/service/dynamodb"
"testing"
)
func TestIsConditionalCheckFailedError(t *testing.T) {
testException := &dynamodb.ConditionalCheckFailedException{}
result := isConditionalCheckFailedError(testException)
if !result {
t.Fail()
}
testTransactionalExceptionRea... |
package main
import (
"fmt"
"net"
)
func main() {
var msg = make([]byte,1000)
localAddr, err := net.ResolveUDPAddr("udp","127.0.0.1:8888")
if err != nil {
fmt.Println(err)
}
remoterAddr, err1 := net.ResolveUDPAddr("udp","127.0.0.1:8889")
if err1 != nil {
fmt.Println(err1)
}
fmt.Println("wait dialud... |
package metricRouter
import (
"sync"
"time"
cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger"
agg "github.com/ClusterCockpit/cc-metric-collector/internal/metricAggregator"
lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric"
mct "github.com/ClusterCockpit/cc-metric-collector/pkg/mul... |
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package spans
import (
"bytes"
"fmt"
"github.com/google/btree"
"github.com/pingcap/tidb/br/pkg/logutil"
"github.com/pingcap/tidb/br/pkg/utils"
"github.com/pingcap/tidb/kv"
)
// Value is the value type of stored in the span tree.
type Value = uint64
/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.