text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"log"
"net/http"
"io/ioutil"
"encoding/json"
)
type Data struct {
Entry []struct {
ID int64 `json:"id,string"`
Messaging []struct {
Message struct {
Mid string `json:"mid"`
Seq int64 `json:"seq"`
Text string `json:"text"`
} `json:"message"`
Recipien... |
package models
type TodoItem struct {
Id int
Title string
Done bool
}
type NewTodoItem struct {
Title string `json:"title"`
}
func (n NewTodoItem) TodoItemModel() *TodoItem {
generatedItem := new(TodoItem)
generatedItem.Title = n.Title
generatedItem.Done = false
return generatedItem
}
func (item TodoItem) ... |
package gominin
import (
"io"
"testing"
)
func TestNewCharTokenizer(t *testing.T) {
tokenizer := newCharTokenizer()
tokenizer.Init([]byte("foo"))
if string(tokenizer.textBytes) != "foo" {
t.Error("Init should initialize tokenizer fields.")
}
if tokenizer.pos != 0 {
t.Error("Init should initialize pos field... |
package main
import "fmt"
func main() {
fmt.Println("test drone -c -n ")
}
|
package domain
import (
"time"
uuid "github.com/satori/go.uuid"
)
type Auth struct {
ID uuid.UUID `db:"id" json:"id"`
UserID uuid.UUID `db:"user_id" json:"user_id"`
AccessToken string `db:"access_token" json:"access_token"`
ExpiredAt time.Time `db:"expired_at" json:"expired_at"`
CreatedAt ... |
package channels
import (
"fmt"
"testing"
)
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}
func TestChannels(t *testing.T) {
/*
채널은 채널 연산자 <- 를 이용해 값을 주고 받을 수 있는, 타입이 존재하는 파이프입니다.
ch <- v // v 를 ch로 보냅니다.
v := <-ch // ch로부터 값을 받아서
... |
package main
import "fmt"
var a []int
func main() {
b := make(chan int)
fmt.Println(b)
go func() {
x := <-b
fmt.Println(x)
}()
b <- 10
}
|
package routes
import (
"github.com/go-chi/chi"
"github.com/jmc-quetzal/api/config"
"github.com/jmc-quetzal/api/handlers"
"github.com/jmc-quetzal/api/postgres"
"github.com/jmc-quetzal/api/redis"
)
func userRoutes(router *chi.Mux, cfg *config.Config) {
pgStore := postgres.UserStore{DB: cfg.DB}
sessionStore := r... |
package math
import "testing"
func TestAverage(t *testing.T) {
_, _, avg, _ := GetStats([]float32{1, 2, 3})
if avg != 2 {
t.Error("Expected 2, got ", avg)
}
}
func TestMin(t *testing.T) {
_, min, _, _ := GetStats([]float32{1, 2, 3})
if min != 1 {
t.Error("Expected 1, got ", min)
}
}
func TestMax(t *testin... |
package problems
// Node Represents a node in a tree.
type Node struct {
Val string
Left *Node
Right *Node
}
|
package piscine
import "fmt"
func PrintWordsTables(table []string) {
for str := range table {
Printstr(str)
z01.PrintRune('\n')
}
}
|
package main
import (
"log"
"sync"
"github.com/PumpkinSeed/concurrent-mysql-benchmark/backend"
"github.com/PumpkinSeed/concurrent-mysql-benchmark/database"
"github.com/PumpkinSeed/concurrent-mysql-benchmark/database/models"
)
const connection = "ec_user:password@tcp(127.0.0.1:3306)/experiment_company"
var wg ... |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
package generate
func generate(numRows int) [][]int {
ret := make([][]int, numRows)
for i := 1; i <= numRows; i++ {
ret[i-1] = make([]int, i)
ret[i-1][0], ret[i-1][i-1] = 1, 1
for j := 1; j < i-1; j++ {
ret[i-1][j] = ret[i-2][j-1] + ret[i-2][j]
}
}
return ret
}
|
//author xinbing
//time 2018/8/30 21:04
package utilities
|
package api
import (
"InkaTry/warehouse-storage-be/internal/http/admin/dtos"
"InkaTry/warehouse-storage-be/internal/pkg/errs"
"InkaTry/warehouse-storage-be/internal/pkg/http/responder"
"InkaTry/warehouse-storage-be/internal/pkg/stores"
"context"
"encoding/json"
"github.com/gorilla/mux"
"github.com/stretchr/tes... |
package app
import (
"github.com/ebar-go/ego/component/log"
"github.com/ebar-go/ego/config"
"github.com/ebar-go/ego/errors"
"github.com/ebar-go/ego/utils"
"github.com/ebar-go/event"
"github.com/go-redis/redis"
"github.com/jinzhu/gorm"
"time"
)
const (
// config init event
ConfigInitEvent = "CONFIG_INIT_EVEN... |
// 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 main
import (
"fmt"
)
func main() {
a := []int{}
fmt.Println(a)
fmt.Printf("Length: %v\n", len(a))
fmt.Printf("Capacity: %v\n", cap(a))
a = append(a,1)
fmt.Println(a)
fmt.Printf("Length: %v\n", len(a))
fmt.Printf("Capacity: %v\n", cap(a))
a = append(a, []int{2, 3, 4, 5}...)
fmt.Println(a)
fmt.Pri... |
package handlers
import (
"bytes"
"encoding/json"
"github.com/bpross/password-as-a-service/stats"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestStatsHandlerInitial(t *testing.T) {
req := httptest.NewRequest("GET", "/stats", nil)
rr := httptest.NewRecorder()
st := stats.New()
Stat... |
package scene
import (
"github.com/mikee385/GolangRayTracer/color"
"github.com/mikee385/GolangRayTracer/geometry"
"math"
)
const Bias = 1.0E-4
type Scene struct {
backgroundColor color.ColorRGB
refractiveIndex float32
maxRayDepth uint
items []internalObject
lights []internalLight
}
func NewScene(backg... |
package data
import (
"github.com/gorilla/websocket"
"github.com/op/go-logging"
"time"
)
var log = logging.MustGetLogger("main-logger")
type WsError struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
type WsEvent struct {
Id int `json:"id"`
Type string `json:"type"`
Channel string `... |
// +build !mysql
package main
import (
"database/sql"
"fmt"
"os"
"strings"
"time"
)
// SCSDB ...
type SCSDB struct {
conn *sql.DB
}
// CreateDBConnection ...
func CreateDBConnection() *SCSDB {
db := SCSDB{}
db.init()
log.Infof("Starting connection....")
return &db
}
// ForcedStatement ...
func (db *SCS... |
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/pkg/errors"
)
const (
url string = "" // バックエンドのURL
)
// サーバがリクエストを受けると、バックエンドのサーバへアクセスする処理をイメージ
// リクエストタイムアウト3秒とし、その際にバックエンドへの接続資源を解放する処理を実装してみる
func main() {
handler()
}
func handler() {
ctx, cancel := context.WithTimeout(co... |
// Copyright 2020, OpenTelemetry 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 a... |
package main
// To judge whether tree2 is the subtree of tree1
func isSubtree(tree1 *TreeNode, tree2 *TreeNode) bool {
if isBothEmptyTree(tree1, tree2) {
return true
}
if isEitherEmptyTree(tree1, tree2) {
return false
}
return isSameTree(tree1, tree2) || isSubtree(tree1.Left, tree2) || isSubtree(tree1.Right, ... |
package sockguard
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"regexp"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
// Credit: http://hassansin.github.io/Unit-Testing-http-client-in-Go
type roundTripFunc func(req *http.Request) *http.Res... |
package carriage
import (
"TruckMonitor-Backend/model"
"fmt"
)
func convertEmployeeName(employee *model.Employee) (result string) {
result = fmt.Sprintf("%s %s", employee.Surname, employee.Name)
if len(employee.Patronymic) > 0 {
result = fmt.Sprintf("%s %s", result, employee.Patronymic)
}
return
}
|
// Copyright The OpenTelemetry 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 agre... |
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
"strconv"
)
func getSelectedCategory(document *goquery.Document) (selectedCategoryNode *goquery.Selection) {
return document.Find("ul ul li span").First()
}
func getAllCategories(document *goquery.Document) (categoriesList []*Category) {
selectedCate... |
package mal
import (
"drdgvhbh/discordbot/internal/cli/anime/mal"
"fmt"
"time"
"github.com/bwmarrin/discordgo"
)
type AnimeStockQuoteEmbeddedOptions struct {
AnimeStock mal.AnimeStock
}
func CreateAnimeStockQuoteEmbedded(
options AnimeStockQuoteEmbeddedOptions,
) *discordgo.MessageEmbed {
animeStock := optio... |
package cmd
import (
"errors"
"time"
boshblob "github.com/cloudfoundry/bosh-agent/blobstore"
bosherr "github.com/cloudfoundry/bosh-agent/errors"
boshlog "github.com/cloudfoundry/bosh-agent/logger"
boshcmd "github.com/cloudfoundry/bosh-agent/platform/commands"
boshsys "github.com/cloudfoundry/bosh-agent/system"... |
package data
import "testing"
func TestPlantStructValidation(testcase *testing.T) {
plant := &Plant{
Name: "apple",
Price: 200.00,
}
validationError := plant.Validate()
if validationError != nil {
testcase.Fatal(validationError)
}
}
|
package micro
import (
"fmt"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/server"
)
func InitServer(name, version string, registry *EtcdRegistry, broker *MqttBroker, fn func(s server.Server)) {
var (
s micro.Service
opts []micro.Option
)
opts = []micro.Option{
micro.Name(name),
micro... |
package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
)
//控制器声明
type BaseController struct {
beego.Controller
}
//返回结构声明
type ReturnData struct {
code int
message string
data map[string]interface{}
}
/**
* 接收参数方法
* @param param interface{} 对应 structs 地址
*/
func... |
package s3
import (
"context"
"crypto/sha256"
"fmt"
"io"
"net/url"
"path"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type S3AO struct {
client *minio.Client
bucket string
expiry time.Duration
}
type BucketInfo struct... |
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Blue Oak Model License
// that can be found in the LICENSE file.
package gc
import (
"context"
"time"
docker "github.com/docker/docker/client"
)
// FilterFunc filters the Docker resource based
// on its labels. If ... |
package main
import (
"log"
"os"
"strconv"
"github.com/grayzone/godcm/core"
"github.com/grayzone/godcm/dcmimage"
)
var folder = "./test/data/"
func readdicmfile(filename string, isReadValue bool) {
var reader core.DcmReader
reader.IsReadValue = isReadValue
err := reader.ReadFile(folder + filename)
if err ... |
package utils
import (
"bufio"
"bytes"
"encoding/gob"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"reflect"
"strconv"
"strings"
"time"
"crypto/sha1"
)
const (
letterAlphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterNumbers = "0123456789"
letterA... |
package fluent
import (
"fmt"
"reflect"
"strconv"
"strings"
)
const scannerTag = "sql"
type scanner struct {
value interface{}
}
type one struct{}
type all struct{}
type scannerType interface {
scan(s interface{}, vals map[string]interface{}) error
}
func (o *one) scan(s interface{}, vals map[string]interfa... |
package InformaCast
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
)
// RestDialCastDialingConfig represents the JSON the API expects to receive.
// The bad naming convention is provided to you by the official InformaCast REST API documentation.
type RestDialCastDialingConfig struct {
id in... |
package receiver
type ExposableError struct {
err string
}
func NewExposableError(err string) ExposableError {
return ExposableError{
err: err,
}
}
func (e ExposableError) Error() string {
return e.err
}
|
package wso2
import (
"bytes"
"crypto/rsa"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v4"
)
var errCantIdentifyKey = fmt.Errorf("Unable to identify key used for signing")
// Client ... |
package operands
import (
"context"
"fmt"
hcov1beta1 "github.com/kubevirt/hyperconverged-cluster-operator/pkg/apis/hco/v1beta1"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/controller/common"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/controller/commonTestUtils"
hcoutil "github.com/kub... |
package boltrepo
import (
"bytes"
"encoding/binary"
"encoding/json"
"github.com/boltdb/bolt"
"github.com/scjalliance/drivestream/binpath"
"github.com/scjalliance/drivestream/collection"
"github.com/scjalliance/drivestream/page"
"github.com/scjalliance/drivestream/resource"
)
var _ page.Sequence = (*Pages)(ni... |
/*
* @lc app=leetcode id=87 lang=golang
*
* [87] Scramble String
*/
func checkScramble(s1, s2 string, cache map[string]bool) bool {
n := len(s1)
if n == 1 {
return s1 == s2
}
if t, ok := cache[s1+" "+s2]; ok {
return t
}
for i := 1; i < n; i++ {
match := (checkScramble(s1[:i], s2[:i], cache) && check... |
package main
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/rightscale/rsc/gen"
)
var _ = Describe("APIAnalyzer ParseRoute", func() {
var (
moniker string
routes []string
pathPatterns []*gen.PathPattern
)
JustBeforeEach(func() {
pathPatterns = ParseRoute(moniker, routes)
... |
package main
import (
"fmt"
)
type Data struct {
}
// 测试方法
func (self Data) String() string {
return "this is string: data"
}
func main() {
fmt.Printf("%v\n", Data{})
}
|
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strconv"
"strings"
"md2cflc/confluence"
"md2cflc/render"
)
var (
username = flag.String("u", "", "Confluence username")
passwd = flag.String("p", "", "Confluence password")
pageId = flag.String("pageid", "", "C... |
//First published go package.
package main
import (
"fmt"
"github.com/andy1341/lets-go-chat/pkg/hasher"
)
func main() {
fmt.Println(hasher.HashPassword("asd"))
fmt.Println(hasher.CheckPasswordHash("asd", "passhash"))
}
|
package peer
import (
"fmt"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/bean"
"sync"
)
type NbrPeers struct {
sync.RWMutex
List map[uint64]*Peer
}
func (np *NbrPeers) Broadcast(msg bean.Message, isConsensus bool) {
np.RLock()
defer np.RU... |
package camt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03600103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.036.001.03 Document"`
Message *DebitAuthorisationResponseV03 `xml:"DbtAuthstnRspn"`
}
func (d *Document03... |
package main
import (
"flag"
"fmt"
"log"
"os"
"path"
"time"
"github.com/codeformuenster/dkan-newest-dataset-notifier/datasets"
"github.com/codeformuenster/dkan-newest-dataset-notifier/externalservices"
"github.com/codeformuenster/dkan-newest-dataset-notifier/s3"
"github.com/codeformuenster/dkan-newest-datas... |
package dbft
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/types"
dposStruct "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/dbft/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/db"
"github.com/HNB-ECO/HNB-Blockchain/HNB/ledger"
"github.com/HNB-ECO/HN... |
package main
import (
"log"
"os"
"fmt"
"github.com/olekukonko/tablewriter"
)
func (app *Application) QueueAction(args []string) {
log.Printf("username = %#v", app.Username)
issues, err1 := app.Client.GetIssuesByAsignee(app.Username)
if err1 != nil {
fmt.Printf("Unable to get user issues: %v\n", err1)
os.... |
package routers
import (
"github.com/gorilla/mux"
"github.com/gotodos/handlers"
"github.com/gotodos/common"
)
func InitRouters() *mux.Router {
router := mux.NewRouter().StrictSlash(false)
taskRoutes := GetTaskRoutes()
taskRouter := common.JwtWrapper(taskRoutes)
router.PathPrefix("/tasks").Handler(taskRouter)... |
// Main canibus server
package main
import (
"flag"
"os"
"github.com/ghetzel/canibus/core"
"github.com/ghetzel/canibus/server"
"github.com/ghetzel/canibus/webserver"
)
const (
DEFAULT_IP = "0.0.0.0"
DEFAULT_PORT = "1234"
DEFAULT_WEBPORT = "2515"
DEFAULT_WWW_ROOT = "www"
DEFAULT_CONFI... |
package commands
// Signup is a command requesting a new customer signup be performed.
type Signup struct {
CustomerID string
Name string
Nickname string
}
// ChangeNickname is a command requesting an existing customer's nickname be
// changed.
type ChangeNickname struct {
CustomerID string
NewNickname ... |
package main
import "syscall"
var syscallType = map[int]int{
syscall.SYS_ACCESS: SyscallPath,
syscall.SYS_CHDIR: SyscallPath,
syscall.SYS_CREAT: SyscallPath,
syscall.SYS_EXECVE: SyscallPath,
syscall.SYS_LCHOWN: SyscallPath,
syscall.SYS_LINK: SyscallPath,
syscall.SYS_LSTAT: Sysc... |
package main
import (
"fmt"
"strings"
"strconv"
)
func pa_test(n int) bool {
// convert n to string sn for parsing
sn := strings.Split(strconv.Itoa(n), "")
// Reverse sn
for i, j := 0, len(sn)-1; i < j; i, j = i+1, j-1 {
sn[i], sn[j] = sn[j], sn[i]
}
srn := strings.Join(sn, "")
// convert re... |
// Copyright 2021 Kuei-chun Chen. All rights reserved.
package keyhole
import (
"github.com/simagix/keyhole/sim"
)
// StartSimulation kicks off simulation
func StartSimulation(runner *sim.Runner) error {
var err error
if err = runner.Start(); err != nil {
return err
}
return runner.CollectAllStatus()
}
|
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 requir... |
/*
Package sqle is a general purpose, transparent, non-magical helper package
for sql.DB that simplifies and reduces error checking for various SQL
operations.
*/
package sqle
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-08 08:30
# @File : lt_113_Path_Sum_II.go
# @Description :
# @Attention :
*/
package v0
/*
找到路径的同时,收集路径
解题思路: dfs解决
*/
func pathSum(root *TreeNode, sum int) [][]int {
result := make([][]int, 0)
dfs(root, sum, []int{}, &result)
return result
}
fun... |
package server
import (
"chlorine/apierror"
"chlorine/storage"
"chlorine/ws"
"encoding/gob"
"fmt"
"log"
"net/http"
"os"
"time"
)
var (
dbStorage *storage.DBStorage
dbConfig = storage.DatabaseConfig{
Host: os.Getenv("POSTGRES_HOST"),
Port: os.Getenv("POSTGRES_PORT"),
User: os.Getenv("POST... |
package primitives_test
import (
"encoding/xml"
"fmt"
"github.com/plandem/xlsx/format"
"github.com/plandem/xlsx/internal/ml/primitives"
"github.com/stretchr/testify/require"
"testing"
)
func TestTimePeriod(t *testing.T) {
type Entity struct {
Attribute primitives.TimePeriodType `xml:"attribute,attr"`
}
li... |
/*
Copyright 2018-2020 The Nori 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, soft... |
package licenses
const (
// LicensesGetLicenses is a string representation of the current endpoint for getting licenses
LicensesGetLicenses = "v1/metadata/getLicenses"
)
|
// Copyright 2012 Derek A. Rhodes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lorem
import (
"math/rand"
"strings"
)
// Generate a natural word len.
func genWordLen() int {
f := rand.Float32() * 100
// a table of word leng... |
package handlers
import (
"coffeebeans-people-backend/models"
"coffeebeans-people-backend/utility"
"context"
"encoding/json"
"net/http"
)
func CreateProject(apiSvc models.ApiSvc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var project models.Project
err := json.NewDecoder(r.Body... |
package 搜索
// -------------------------------- 搜索 --------------------------------
func numWays(n int, relation [][]int, k int) int {
canReach := get2DSlice(n, n)
for i := 0; i < len(relation); i++ {
canReach[relation[i][0]][relation[i][1]] = true
}
return getNumWays(n, canReach, 0, k)
}
func getNumWays(n int, ... |
package jqka
import (
"bytes"
"fmt"
"time"
. "../"
. "../../base"
"github.com/golang/glog"
)
const tout time.Duration = time.Second * 10
type JQKARobot struct {
RobotBase
}
func init() {
for i := DefaultRobotConcurrent; i > 0; i-- {
robot := &JQKARobot{}
Registry(robot)
}
}
func (p *JQKARobot) Can(id... |
package compute
const (
// AssetTypeServer is an asset type representing a server.
AssetTypeServer = "SERVER"
// AssetTypeNetworkDomain is an asset type representing a network domain.
AssetTypeNetworkDomain = "NETWORK_DOMAIN"
// AssetTypeVLAN is an asset type representing a virtual LAN (VLAN).
AssetTypeVLAN = ... |
// Copyright 2019-2023 The sakuracloud_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... |
package acme
import (
"bytes"
"context"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"golang.org/x/crypto/acme"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
"github.com/jetstack-experimental/cert-manager/pkg/apis/certmanager/v1alpha1"
"github.com/jetstack-experimental/cert-manager/pkg/util/kub... |
package grid
type GridRepository interface {
GetDimensions() (int, int)
Draw()
CalculateNexGeneration() error
}
|
package main
import (
"flag"
"fmt"
log "gopkg.in/Sirupsen/logrus.v0"
"github.com/mackee/kuiperbelt"
)
func main() {
var configFilename, logLevel, port, sock string
var showVersion bool
flag.StringVar(&configFilename, "config", "config.yml", "config path")
flag.StringVar(&logLevel, "log-level", "", "log leve... |
package criteria
import (
"fmt"
"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"
"github.com/pomerium/pomerium/pkg/webauthnutil"
)
const (
deviceOperatorApproved = "appro... |
package spotbot
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/CloudCom/firego"
)
type Track struct {
duration float64
uri string
title string
artist string
}
func (track Track) String() string {
res := fmt.Sprintf("%s - %s", track.title, track.artist)
return r... |
package main
import (
"bufio"
//"bytes"
"encoding/json"
"errors"
"flag"
"github.com/nsqio/go-nsq"
"io/ioutil"
"log"
"net/http"
"sync"
)
var route = make(map[string]bool)
var exitchan = make(chan bool)
var msgchan = make(chan *nsq.Message, 10000)
var producers = make(map[string]*nsq.Producer)
var consume... |
package ds
/**
*
*
*
* Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Outpu... |
package main
import (
"BackendGo/router"
"BackendGo/server"
"log"
)
func main() {
app, err := server.NewServer()
if err != nil {
log.Fatal(err)
}
if err = router.ApplyRoutes(app); err != nil {
log.Fatal(err)
}
if err = app.Router.Run(); err != nil {
log.Fatal(err)
}
}
|
package cloudinit
import (
"fmt"
)
// ErrDataNotSupplied error returned of no user-data or network configuration
// in the Secret
type ErrDataNotSupplied struct {
DocName string
Key string
}
func (e ErrDataNotSupplied) Error() string {
return fmt.Sprintf("Document %s has no key %s", e.DocName, e.Key)
}
|
package sessionhub
import (
"github.com/game-explorer/animal-chess-server/internal/pkg/log"
"testing"
"time"
)
// 测试 在放入管道的同时修改管道
// 结果: 已经阻塞到select中的管道依然保持原样(阻塞), 等到下一次写入时才是新的管道生效.
func TestSetChanWrite(t *testing.T) {
var c chan int
go func() {
for range time.Tick(1 * time.Second) {
select {
case c <-... |
package models
type CommentWrap struct {
Json CommentJson `json:"json"`
}
type CommentJson struct {
Errors []string `json:"errors"`
Data CommentJsonData `json:"data"`
}
type CommentJsonData struct {
Things []CommentJsonDataThing `json:"things"`
}
type CommentJsonDataThing struct {
Kind string ... |
package main
import "fmt"
func main() {
a := 4
b := 3
fmt.Println("soma = ", a+b)
fmt.Println("subtração = ", a-b)
fmt.Println("multiplicação = ", a*b)
fmt.Println("divisão = ", a/b)
fmt.Println("módulo = ", a%b)
//bitwise
fmt.Println("AND = ", a&b)
fmt.Println("OR = ", a|b)
fmt.Println("XOR = ", a^b)
}
|
package utils
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
)
var DEBUG bool = false
type UserOptions struct {
Print bool
PrintSleepMiliseconds int
}
func Println(a ...interface{}) (n int, err error) {
if !DEBUG{
return
}
return fmt.Println(a...)
}
func Max(v1 int, v2 int) int{
if v1 > v2{
return v1... |
package linkedlist
import (
"testing"
)
func TestHasCycleWithUnCycledList(t *testing.T) {
l := newListNodes([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, false)
if hasCycle(l) {
t.Fail()
}
}
func TestHasCycleWithCycledList(t *testing.T) {
l := newListNodes([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, true)
if !hasCycle(l) {
... |
package main
import "fmt"
type Cx struct {
Num int // 当前的跑了第几次
Left []int // 保存在左侧的数
Right []int // 保存在右侧的数据
}
func main() {
num := []int{1,4,2,3,5,9,10,11,24,14,34,13,45,17,19,40}
back := compare(num)
fmt.Println(back)
}
func compare(value []int)[]int{
if len(value)==1 {
return value
}
if len(value) ==... |
package main
import (
"./protocol"
"bufio"
"log"
"os"
"strconv"
)
func main() {
log.Printf("Started Client")
for _, param := range os.Args[1:] {
log.Printf("Registering Server: " + param)
protocol.Connect(param)
}
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
val, err := strconv.Atoi(input.Te... |
// 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 httpexpect
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"github.com/valyala/fasthttp"
)
// Binder implements networkless http.RoundTripper attached directly to
// http.Handler.
//
// Binder emulates network communication by invoking given http.Handler
// directly. It passes httptes... |
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 ... |
/*
* @lc app=leetcode.cn id=1323 lang=golang
*
* [1323] 6 和 9 组成的最大数字
*/
package main
// @lc code=start
func maximum69Number(num int) int {
divider := 1000
for divider > 0 {
if num/divider%10 == 6 {
return num + 3*divider
}
divider /= 10
}
return num
}
// func main() {
// fmt.Println(maximum69Number(... |
package entity
import "time"
//用户
type User struct {
Id int32
Name string
Password string
Email string
CreateTime time.Time
Sign string `orm:"type(text)"`
Role int32 //角色,1 作者,2 游客
UpdateTime time.Time
}
type UserSetting struct{
Id int32 //userId
Photo string `orm:"type(text)"` //头像️,这个是base64存储
SelfInfo ... |
package office
type login struct {
UserName string `json:"userName"`
Password string `json:"password"`
}
type loginRes struct {
Count int `json:"count"`
Status int `json:"status"`
StatusCode int `json:"statuscode"`
Response struct {
Token string `json:"token"`
Expires string `json:"expires"`
... |
// 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 main
import (
"github.com/felipeagger/go-redis/cache"
)
func init() {
cache.InitCacheClientSvc("0.0.0.0", "6379", "")
cache.InitCacheClusterClientSvc("0.0.0.0", "7005", "")
}
func main() {
cache.GetCacheClient().HSet("test", "key", "value")
cache.GetCacheClusterClient().HSet("test", "key", "value... |
package orm
import (
"laravel-go/pkg/orm/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func NewMysqlConn(conn config.ConnParam) *gorm.DB {
dsn := conn.Username + ":" + conn.Password + "@tcp(" + conn.Host + ":" + conn.Port + ")/" + conn.Database + "?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Op... |
package chip
import (
"fmt"
"log"
"os"
"time"
"github.com/veandco/go-sdl2/sdl"
)
var memory [4096]byte
var register [16]byte
var opCode uint16
var index uint16
var delayTimer byte
var soundTimer byte
var programCounter uint16
var stackPointer uint8
var stack [16]uint16
var pixel [][]bool
var running = true
var ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.