text stringlengths 11 4.05M |
|---|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//532. K-diff Pairs in an Array
//Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a ... |
package SecretsManager
import "github.com/aws/aws-sdk-go/service/secretsmanager"
// @deprecated
func GetSecret(manager *secretsmanager.SecretsManager, secretName string) (*string, error) {
return GetSecretString(secretName)
}
|
package misc
import (
"bytes"
"fmt"
"os/exec"
gouuid "github.com/nu7hatch/gouuid"
)
type Meta4 struct {
Dst string
}
func (m Meta4) Create(file File) (string, error) {
fileUUID, err := gouuid.NewV4()
if err != nil {
return "", fmt.Errorf("Generating metalink uuid: %s", err)
}
meta4Path := "/tmp/metalink... |
package raft
import (
"fmt"
"math/rand"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
type testCommand struct {
Msg string
}
func (this *testCommand) CommandName() string {
return "testCommand"
}
func TestMakeRaft(t *testing.T) {
//debug = 1
peers := map[string]string{
"1": "127.0.0.1:6000",
"... |
/**
* WordPress Tickets
* https://cixtor.com/
* https://github.com/cixtor/wptickets
* https://codex.wordpress.org/Using_the_Support_Forums
* https://wordpress.org/support/
*
* Visualize the status of multiple support requests for a WordPress plugin.
*
* The WordPress Support Forums are a fantastic resource wit... |
package main
import "fmt"
type usuario struct {
name string
age uint8
}
func (u usuario) esAdulto() bool {
return u.age >= 18
}
func (u *usuario) hacerCumpleanos() {
u.age++
}
func main() {
usuario1 := usuario{"mario", 18}
fmt.Println(usuario1)
fmt.Println(usuario1.esAdulto())
fmt.Println("---------")
... |
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
net "github.com/fabricioism/go-text-classification/net/processing"
"github.com/go-chi/chi/v5"
)
// Request type.
// This Struct contains the payload
type Request struct {
Sentence string `json:"sentence"`
}
// Response type
// This St... |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
var (
twoRepeats int
threeRepeats int
commonLetters []byte
lines []string
)
func main() {
f, err := os.Open("../input.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
parseLine(s.Text())
}
... |
// Copyright 2014 Brett Slatkin
//
// 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 handlers
import (
"context"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
sink "github.com/go-sink/sink/pkg/sink/v1"
)
// Registrar is registrar of gRPC and gRPC-Gateway handlers.
type Registrar struct {
sinkServer sink.SinkServiceServer
}
// NewRegistrar returns new reg... |
package controllers
import "github.com/gin-gonic/gin"
func (this *TransactionController) Pay(c *gin.Context) {
}
|
package vpcblock
import (
"context"
"fmt"
nfsstoragev1alpha1 "github.com/johandry/nfs-operator/api/v1alpha1"
"github.com/johandry/nfs-operator/resources"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//25. Reverse Nodes in k-Group
//Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
//k is a positive in... |
package pnet
import (
"bytes"
"io/ioutil"
"testing"
)
func TestGeneratedPSKCanBeUsed(t *testing.T) {
psk := GenerateV1PSK()
_, err := NewProtector(psk)
if err != nil {
t.Fatal(err)
}
}
func TestGeneratedKeysAreDifferent(t *testing.T) {
psk1 := GenerateV1PSK()
psk2 := GenerateV1PSK()
bpsk1, err := ioutil... |
package glc
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestGLC(t *testing.T) {
files := []string{"glc.localhost.xuri.log.WARNING.20180312-144710.3877", "glc.localhost.xuri.log.WARNING.20180312-144710"}
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
t.Error(err)
return
}
pa... |
package goSolution
import "testing"
func TestLongestStrChain(t *testing.T) {
words := []string {"xbc","pcxbcf","xb","cxbc","pcxbc"}
AssertEqual(t, 5, longestStrChain(words))
}
|
package menu
import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"math"
"projja_telegram/command/projects/controller"
"projja_telegram/command/util"
"projja_telegram/model"
"strings"
)
func MakeProjectsMenu(message *util.MessageData, page int, count int) (tgbotapi.MessageConfig, []*model.... |
package yadisk
import (
"context"
"io"
"net/http"
"reflect"
"testing"
"time"
)
var (
duration2 = time.Duration(2) * time.Second
)
func createClient(ctx context.Context, url string) *client {
client, _ := newClient(ctx, &testValidToken, url, 1, http.DefaultClient)
return client
}
func createContextWithTimeo... |
package graphql
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"text/template"
"time"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
// GeneratedFilesPath defines where to put files created from parsing the schema
var GeneratedFilesPath = "./generated"
var schema Schema
type (
// Schema rep... |
package queries
import (
"database/sql"
"encoding/json"
"net/url"
"strconv"
"github.com/pwang347/cs304/server/common"
)
// CreateServiceSubscriptionTransaction creates a new service subscription
func CreateServiceSubscriptionTransaction(db *sql.DB, params url.Values) (data []byte, err error) {
var (
result ... |
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/jj40308/dcard-ratelimit-middleware/lib"
"net/http"
"strconv"
)
type RateLimiter struct {
rateLimit *lib.RateLimit
}
func NewRateLimiter(rateLimit *lib.RateLimit) *RateLimiter {
return &RateLimiter{
rateLimit: rateLimit,
}
}
func (r *RateLim... |
package schema
import (
"github.com/clems4ever/go-graphkb/internal/utils"
)
type AssetValidationFunc func(string) bool
type ValidationRegistry interface {
Get(AssetType) ([]AssetValidationFunc, bool)
}
var (
AssetValidationRegistry ValidationRegistry = utils.NewRegistry[AssetType, []AssetValidationFunc]()
)
fun... |
package rest_test
import (
"net/http"
"path/filepath"
"encoding/json"
"testing"
"github.com/iris-contrib/httpexpect"
r "github.com/jinmukeji/jiujiantang-services/api-jinmuid/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// SmsSuite 是Sms的单元测试的 Test Suite
type SmsSuite struc... |
// 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 xhhttp
import (
"crypto/tls"
"fmt"
"github.com/cyongxue/magicbox/xhiris/xhid"
"github.com/cyongxue/magicbox/xhiris/xhlog"
"github.com/kataras/iris/v12"
"io/ioutil"
"net/http"
"strings"
"time"
)
type NetHttp struct {
Method Method
Url string
IsHttps bool
}
// Send 发送http请求
func (n *NetHttp) S... |
import "math/rand"
type Solution struct {
orig []int
}
func Constructor(nums []int) Solution {
return Solution{
orig: nums,
}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.orig
}
/** Returns a random shuffl... |
package main
import (
"os"
"net/http"
"github.com/gorilla/mux"
"html/template"
"log"
"encoding/json"
"fmt"
api "github.com/ManojChandran/webapp/api"
)
var templates *template.Template
type configuration struct {
PORT string
ROOT string
SHUTDOWN string
STATIC ... |
// Package redis implements a Redis backed session manager for RiveScript.
package redis
// NOTE: This source file contains the implementation of a SessionManager.
import (
"fmt"
"strings"
"time"
"github.com/aichaos/rivescript-go/sessions"
redis "gopkg.in/redis.v5"
)
// Config allows for configuring the Redis ... |
package rpc
type Method string
type ErrorCode int
const (
ParseError = -32700
InvalidRequest = -32600
MethodNotFound = -32601
InvalidParams = -32602
InternalError = -32603
ProviderNotFound = -32001
RequestMissingProviderId = -32002
AppointmentWas... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
)
const productVersion = "1.1.1"
func main() {
configFile := flag.String("config", "config.yaml", "Config file location")
initiate := flag.Bool("init", false, "Create initial config file")
version := flag.Bool("v", false, "Print product v... |
package middlewares
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/lenuse/mall/utils"
)
func SetTraceId() gin.HandlerFunc {
return func(ctx *gin.Context) {
_, exists := ctx.Get(utils.TraceIdKey)
if !exists {
id := uuid.New().String()
ctx.Set(utils.TraceIdKey, id)
}
ctx.Next... |
// Copyright 2016 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 logger
import (
"errors"
"os"
"sync"
slog "github.com/Nyks06/go-syslog"
)
//Type is the one type used to define CONSOLE, FILE, ... - the type of our logger
type outType uint8
type logLevel uint8
type logColor string
//Status is just a bool used to change the status of a certain type of loggers
type st... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2019-11-28 10:53
# @File : error.go
# @Description : error 封装
*/
package error
import "errors"
const (
RESULT_LEVEL_SUCCESS = 1
// 返回原生的错误,对原生的信息不包装成其他类型的错误
RESULT_RETURN_NATIVE_ERR = RESULT_LEVEL_SUCCESS << 1
)
type WrapErrFunc func(int2 int, msg string) e... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/11/29 9:24 上午
# @File : lt_238_除自身数组以外的乘积.go
# @Description :
# @Attention :
*/
package v2
// 关键: 当前数 = 左边的乘积 * 右边的乘积
// 如: 2,4,6,8 对于下标 2的值: 左边的乘积=2*4 右边的乘积=8 => 2*4*8
// 但是还有很关键的一点是,左边的起始为1 ,右边末尾结尾也是为1
func productExceptSelf(nums []int) []int {
l, r, re... |
package schema
import "context"
// Persistor is a persistor of schema
type Persistor interface {
SaveSchema(ctx context.Context, sourceName string, sg SchemaGraph) error
LoadSchema(ctx context.Context, sourceName string) (SchemaGraph, error)
}
|
// Copyright 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, softwar... |
package actions
import (
"fmt"
"net/http"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/pop/v5"
"github.com/gobuffalo/x/responder"
"github.com/tcarreira/roaw2020/models"
stravaclient "github.com/tcarreira/roaw2020/strava_client"
"github.com/tcarreira/roaw2020/strava_client/swagger"
)
// ListUsersHand... |
package spaghetti
import (
"errors"
"strings"
"syscall/js"
n "github.com/lachee/noodle"
)
/**
ResourceResult is a tuple that contains the JS value and any errors that were created from the resource.
Spaghetti itself contains nothing on the Go side to resolve the resources, that is all handled with the wrapper sp... |
package simulation_test
import (
"fmt"
"math/big"
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/irisnet/irismod/modules/random/simulation"
"github.com/irisnet/irismod/modules/random/types"
"github.com/irisnet/iri... |
package queue
import (
"context"
"encoding/json"
"github.com/chitoku-k/ejaculation-counter/supplier/infrastructure/config"
"github.com/chitoku-k/ejaculation-counter/supplier/service"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promaut... |
package model
import (
"encoding/json"
"fmt"
"go_code/project1/94chatroom/common/message"
"github.com/garyburd/redigo/redis"
)
//服务器启动后,就初始化一个UserDao实例,所有的DML操作都公用这个
var (
MyUserDao *UserDao
)
// 定义一个UserDao结构体
// 完成对User结构体的各种操作
type UserDao struct {
pool *redis.Pool
}
//使用工厂模式,创建一个UserDao实例
func NewUserDa... |
package model
import (
"database/sql"
"github.com/CourseComment/conf"
_ "github.com/go-sql-driver/mysql"
//"os"
//"time"
)
type idtype int32
var (
db *sql.DB
)
func init() {
db = conf.DB
}
|
package fantasyfootball
import (
"math"
"runtime"
"sort"
"strings"
)
const (
START_DEPTH = 4
)
type FantasyDraft struct {
players []*FantasyPlayer
maxPlayer *FantasyPlayer
playersDrafted int
dsts *Stack
ks *Stack
qbs *Stack
rbs *Stack
tes ... |
package user
import (
"encoding/csv"
"io"
"strings"
)
type (
Users []User
)
func (users *Users) ReadFrom(r io.Reader) (int64, error) {
reader := csv.NewReader(r)
records, err := reader.ReadAll()
c := 0
if err != nil {
return int64(c), err
}
for _, row := range records {
*users = append(*users, User{
... |
package main
import (
"bloom-clock/operations"
"errors"
"github.com/DATA-DOG/godog"
)
var (
timestamp1 []byte
timestamp2 []byte
comparable bool
firstBig, secondBig int
)
// Step
func twoTimestamps() error {
timestamp1 = []byte{1, 0, 0, 1}
timestamp2 = []byte{1, 1, 0, 1}
return n... |
package main
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/rightscale/rsc/cm15"
"github.com/rightscale/rsc/cm16"
"github.com/rightscale/rsc/cmd"
"github.com/rightscale/rsc/ss"
"gopkg.in/alecthomas/kingpin.v2"
)
var _ = Describe("Command line parsing", func() {
Context("wit... |
package hghstring
import (
"fmt"
"time"
)
func ExampleParse() {
timeDuration := (364 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
duration := Parse(timeDuration).String()
fmt.Println(duration)
}
|
package main
import (
"fmt"
"math"
"strconv"
)
type Primes []bool
func make_sieve(max int) Primes {
p := make(Primes,max,max)
smax := math.Sqrt(float64(max)) + 1
for x := 2; float64(x) < smax; x++ {
if p[x] != true {
for y := x + x ; y < max; y+=x {
p[y]=true
}
}
... |
package hls
import (
"context"
"fmt"
"time"
"github.com/grafov/m3u8"
"github.com/shaunschembri/restreamer/pkg/restream/provider"
"github.com/shaunschembri/restreamer/pkg/restream/request"
)
const mbDivider = 1048576
type Media struct {
request request.Request
playlistURL string
lastMediaSeq uint64
}... |
package main
import (
"fmt"
"net"
"os"
"strings"
"typeDefine"
)
var Muser *typeDefine.TotalUser
func main() {
Muser.OnlineUser = make([]*typeDefine.User, 0, 10)
service := ":8282"
tcpAddr, err := net.ResolveTCPAddr("tcp", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(e... |
/*
Given an unsorted array of integers, sort the array into a wave array. An array arr[0..n-1] is sorted in wave form if:
arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= …..
Examples:
Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80}
Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80}
Explanation:
here you can see {10, 5, 6... |
package main
import (
api "github.com/kevinbarbary/go-lms/api"
html "github.com/kevinbarbary/go-lms/html"
utils "github.com/kevinbarbary/go-lms/utils"
"net/http"
"strconv"
)
func learn(w http.ResponseWriter, r *http.Request, enrollId int) {
var enrolStr string
if enrollId > 0 {
enrolStr = strconv.Itoa(enrol... |
// Copyright 2018 The Hugo Authors. 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 ... |
package auth
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/go-redis/redis"
)
type AuthRepo interface {
getLogin(string) (*Login, error)
update(*Login) (bool, error)
create(*Login) (*Login, error)
storeToken(int, *StoredToken) (*StoredToken, error)
retrieveToken(int) (*StoredTok... |
package entity
type OmsCompanyAddress struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20) 'id'"`
AddressName string `json:"address_name" xorm:"default 'NULL' comment('地址名称') VARCHAR(200) 'address_name'"`
SendStatus int `json:"send_status" xorm:"default NULL comment('默认发货地址:0->否;1->是') INT(... |
package mxdisk
import (
"fmt"
"sort"
)
// DiskSummary is info for disk and partition state
type DiskSummary struct {
MntDiskInfo
SysBlockInfo
UdevInfo
Fstab
}
// DisksSummaryMap map of disks
type DisksSummaryMap map[string]DiskSummary
func newDisksSummaryMap() DisksSummaryMap {
return make(DisksSummaryMap)
}... |
package main
import (
"bytes"
"fmt"
"github.com/restic/restic/backend"
"github.com/restic/restic/debug"
"github.com/restic/restic/pack"
"github.com/restic/restic/repository"
)
type CmdRebuildIndex struct {
global *GlobalOptions
repo *repository.Repository
}
func init() {
_, err := parser.AddCommand("rebui... |
package keyboard
import (
"fmt"
"sync"
"github.com/nsf/termbox-go"
"github.com/siggy/bbox/bbox"
log "github.com/sirupsen/logrus"
)
type tbcell struct {
x int
y int
termbox.Cell
}
// normal operation:
// keyboard -> emit
type Keyboard struct {
keyMap map[bbox.Key]*bbox.Coord
pressed chan bbox.Coord // s... |
// Package wav is direct WAV filo I/O
package wav
import (
// "github.com/stretchr/testify/assert"
"testing"
)
func TestReaderOpen(t *testing.T) {
// TODO
}
func TestReaderFormat(t *testing.T) {
// TODO
}
func TestReaderReadSamples(t *testing.T) {
// TODO
}
func TestReaderReadSamplesIntoBuffer(t *testing.T) {... |
package log
import (
"io"
"log"
)
/* TODO:
- Should possibly add Debug, Debugf type helper methods
*/
type LogLevel int8
var minLevel LogLevel
const (
DEBUG LogLevel = iota
TRACE
INFO
WARN
ERROR
FATAL
PANIC
)
func (l LogLevel) String() string {
switch l {
case DEBUG:
return "DEBUG "
case TRACE:
re... |
package configor
import (
"encoding/json"
"io/ioutil"
"os"
"reflect"
"testing"
)
type Anonymous struct {
Description string
}
type testConfig struct {
APPName string `default:"configor" json:",omitempty"`
Hosts []string
DB struct {
Name string
User string `default:"root"`
Password string `r... |
package frida_go
import (
"context"
"errors"
"fmt"
"github.com/a97077088/frida-go/cfrida"
"github.com/json-iterator/go"
"log"
"math"
"sync"
"unsafe"
)
const (
RpcOperation_call = "call"
)
const (
RpcKind_default = "frida:rpc"
)
var reqlk sync.Mutex
var rpcRequestId int64
func nextRpcRequestId() int64 {
... |
// This sample program demonstrates how to create goroutines and
// how the goroutine scheduler behaves with three logical processors.
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
// Allocate three logical processors for the scheduler to use.
runtime.GOMAXPROCS(3)
// proc... |
package db
import (
"context"
"database/sql"
)
func Tx(ctx context.Context, db *sql.DB, fn func(tx *sql.Tx) error) error {
isSuccess := false
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() {
if !isSuccess {
_ = tx.Rollback()
}
}()
if err := fn(tx); err != nil {
return er... |
/*
Copyright 2022 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 urlutil
import (
"fmt"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"time"
"github.com/google/uuid"
"google.golang.org/protobuf/encoding/protojson"
"github.com/pomerium/pomerium/internal/version"
"github.com/pomerium/pomerium/pkg/grpc/identity"
"github.com/pomerium/pomerium/pkg/hpke"
)
// HPKEP... |
package commands
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"github.com/argoproj/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/fields"
"github.com/argoproj/argo/cmd/argo/commands/client"
workflowpkg "github.com/argoproj/argo/pkg/apiclient/workflow"
)
type setOps struct {
mes... |
package hot100
// 关键: 链表已经排序
// 还要注意,可能头节点被删除,所以1. 要有dummy 2. 开始的节点不能是dummy#Next
// 因为要删除所有重复元素,而不是只保留一个,所以 必须用next 和next.next 去匹配
func deleteDuplicates(head *ListNode) *ListNode {
dummy := &ListNode{}
dummy.Next = head
var rmValue int
for temp := dummy; temp.Next != nil && temp.Next.Next != nil; {
if temp.Next... |
package config
import (
"github.com/benka-me/laruche/go-pkg/config"
"github.com/joho/godotenv"
"os"
)
const (
PgDatabase = "users"
PgCollection = "users"
)
type Config struct {
DbUser string
DbHost string
DbPort string
DbPWD string
DbSSL string
}
func Init(dev bool) *Config {
envPath := config.Source... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//623. Add One Row to Tree
//Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth ... |
package crypto
import (
"golang.org/x/crypto/bcrypt"
)
func HashPasswd(passwd string) (hash string, err error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(passwd), 12) //TODO: Add to config.
return string(bytes), err
}
func CheckPasswdHash(passwd, hash string) (ok bool) {
err := bcrypt.CompareHashAndPassw... |
package main
import (
"fmt"
)
func main() {
s1 := []int{1, 2, 3, 4, 5}
s2 := []int{7, 8, 9}
//copy(s1, s2) //s1: [7 8 9 4 5], s2: [7 8 9]
copy(s2, s1) //s1: [1 2 3 4 5], s2: [1 2 3]
fmt.Println(s1, s2)
}
|
package flow
import (
"fmt"
"testing"
"github.com/BaritoLog/go-boilerplate/saramatestkit"
"github.com/BaritoLog/go-boilerplate/slicekit"
. "github.com/BaritoLog/go-boilerplate/testkit"
)
func TestKafkaAdmin_RefreshTopics_ReturnError(t *testing.T) {
client := saramatestkit.NewClient()
client.TopicsFunc = func(... |
package api_test
import (
"context"
"errors"
"testing"
"github.com/odpf/stencil/models"
stencilv1 "github.com/odpf/stencil/server/odpf/stencil/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestList(t *testing... |
package event_service
import (
"ms/sun_old/base"
"ms/sun/servises/log_service"
"ms/sun/shared/config"
"ms/sun/shared/x"
"time"
)
//todo: change sub.Deleted_Post_Event <- gEvent # to a func with an select timeout in case event not procceed
func NewSub(param SubParam) Sub {
last := 0
sub := newSub()
go func() {... |
package main
import (
"fmt"
"math"
)
func main() {
sum := float64(0)
for i := 0; i < 20; i++ {
sum += float64(2*i+1) / math.Pow(2, float64(i))
}
fmt.Printf("%.2f\n", sum)
}
|
package env_test
import (
"testing"
"github.com/nasermirzaei89/env"
"github.com/stretchr/testify/assert"
)
func TestEnv_String(t *testing.T) {
v := "testing"
t.Setenv("ENV", v)
res := env.Environment()
assert.EqualValues(t, v, res)
}
func TestEnvironment(t *testing.T) {
assert.Zero(t, env.Environment())
... |
package utils
import (
// "encoding/json"
"fmt"
"github.com/go-chi/render"
"html/template"
"net/http"
)
type StaticMessage struct {
CssClass string
Message string
}
func Message(status bool, message string) map[string]interface{} {
return map[string]interface{}{"status": status, "message": message}
}
func ... |
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
"sync"
"time"
gnmipb "github.com/openconfig/gnmi/proto/gnmi"
pb "github.com/polarbroadband/gnmi/pkg/gnmiprobe"
"github.com/polarbroadband/goto/util"
"github.com/gorilla/handlers"
"github.... |
// 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... |
/*
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 writ... |
package criteria
import (
"github.com/open-policy-agent/opa/ast"
"github.com/pomerium/pomerium/pkg/policy/generator"
"github.com/pomerium/pomerium/pkg/policy/parser"
"github.com/pomerium/pomerium/pkg/policy/rules"
)
var emailBody = ast.Body{
ast.MustParseExpr(`
session := get_session(input.session.id)
`),
a... |
package mqtt
import (
"errors"
"strconv"
"time"
"github.com/casaplatform/casa"
"github.com/gomqtt/client"
"github.com/gomqtt/packet"
)
type Client struct {
timeout time.Duration
client *client.Client
options *client.Config
session client.Session
callback client.Callback
logger client.Logger
userC... |
package middlewares
import (
"io"
"net/http"
"net/url"
"github.com/valyala/fasthttp"
)
// AutheliaHandlerFunc is used with the NewHTTPToAutheliaHandlerAdaptor to encapsulate a func.
type AutheliaHandlerFunc func(ctx *AutheliaCtx, rw http.ResponseWriter, r *http.Request)
type netHTTPBody struct {
b []byte
}
//... |
package main
import (
"flag"
"fmt"
"io"
"net/http"
"time"
"github.com/boltdb/bolt"
)
func main() {
serverAddr := flag.String("server-addr", "", "address of the server")
dbs := flag.String("db", "", "path to db")
flag.Parse()
for i := 0; i < 20; i++ {
go routines(i)
}
if len(*serverAddr) == 0 {
http... |
package mq
import (
"context"
"fmt"
"github.com/streadway/amqp"
)
type consume struct {
delivery <-chan amqp.Delivery
handler Handler
}
// PublishFunction for publish message to mq.
type PublishFunction func(ctx context.Context, data []byte) error
// Handler message from mq.
type Handler func(ctx context.Con... |
package handler
import (
"encoding/json"
"github.com/abdulrahmank/solver/tic_tac_toe/solver"
"github.com/abdulrahmank/solver/tic_tac_toe/ttt"
"net/http"
)
func Play(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
boardJson := &BoardJson{}
if err := json.NewDecoder(r.Body).Decode(&boardJson)... |
//hello.proto and this code is taken from: https://github.com/kenshaw/go-jakarta/tree/master/02-gomobile-and-grpc
package main
import (
"errors"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// A wrapper type to expose via gomobile.
type HelloClient struct {
conn *grpc.ClientConn... |
package im
import (
"log"
"github.com/wst-libs/wst-sdk/conf"
)
// IMConf is a struct
type IMConf struct {
Server struct {
Appname string `yaml:"appname"`
Httpport string `yaml:"httpport"`
Runmodel string `yaml:"runmode"`
Copy bool `yaml:"copyrequestbody"`
Endpoint string `yaml:"endpoint"`
... |
package apis
import (
"github.com/egnis/server/router/apis/handlers"
"github.com/labstack/echo"
)
func BindAdminGroup(e *echo.Group, dbHandler *handlers.DBHandler) {
e.POST("/login", dbHandler.Login)
}
|
package cli
import (
"fmt"
"github.com/irisnet/irishub/tests"
sdk "github.com/irisnet/irishub/types"
"github.com/stretchr/testify/require"
"testing"
)
func TestIrisCLIBankSend(t *testing.T) {
t.Parallel()
chainID, servAddr, port, irisHome, iriscliHome, p2pAddr := initializeFixtures(t)
flags := fmt.Sprintf("-... |
package go_crawl
import (
"fmt"
"os"
"path/filepath"
//"io/ioutil"
)
// func input() string {
// scan := bufio.NewScanner(os.Stdin)
// fmt.Print("Input URL: ")
// scan.Scan()
// Homepage := scan.Text()
// if !(strings.Contains(Homepage, "://")) {
// Homepage = "http://" + Homepage
// if !(strings.Contain... |
// Package config 通用配置接口
package config
import (
"context"
"encoding/json"
"errors"
"strconv"
"sync"
"github.com/BurntSushi/toml"
yaml "gopkg.in/yaml.v3"
)
// ErrConfigNotSupport 尚未支持
var ErrConfigNotSupport = errors.New("app/config: not support")
// GetString 根据key获取string类型的值
func GetString(key string) (s... |
package shutil
import (
"io"
"os"
"syscall"
)
// Copies a file from src to dst.
func CopyFile(src, dst string) error {
var (
f *os.File
g *os.File
err error
)
if f, err = os.Open(src); err != nil {
return err
}
defer f.Close()
if g, err = os.Create(dst); err != nil {
return err
}
defer g.C... |
package main
import app "github.com/sunney-x/projects/cmd"
func main() {
if err := app.Run(); err != nil {
panic(err)
}
}
|
package model
import (
"posthis/database"
)
type FollowModel struct {
Model
}
func (fm FollowModel) GetFollows(id, viewerId uint) ([]FollowUserVM, error) {
models := []FollowUserVM{}
rows, err := database.DB.Raw("CALL SP_GET_FOLLOWERS(?,?)", id, viewerId).Rows()
if err != nil {
return nil, err
}
for rows... |
package ioutils
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
)
// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}... |
types.MigrateUserTable(postgres.POSTGRES)
fmt.Println("Migrated: user")
// HOFSTADTER_BELOW
|
package 位运算
func hammingWeight(num uint32) int {
countOfOne := 0
for num != 0 {
num = removeLowestOne(num)
countOfOne++
}
return countOfOne
}
func removeLowestOne(num uint32) uint32 {
num ^= getValueOfLowestBit(num)
return num
}
// 这样也可以
func removeLowestOne(num uint32) uint32 {
num &= (num - 1)
return n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.