text stringlengths 11 4.05M |
|---|
package main
import (
"github.com/chqsark/dpclustering"
matrix "github.com/skelterjohn/go.matrix"
"fmt"
"math/rand"
/*
"code.google.com/p/plotinum/plot"
"code.google.com/p/plotinum/plotter"
"code.google.com/p/plotinum/plotutil"
*/
)
func norm(min, max float64) float64 {
return rand.Float64() * (max - min)... |
package main
//分治,涉计递归
func mergeKLists(lists []*ListNode) *ListNode {
n := len(lists)
if n == 0 {
return nil
}
if n == 1 {
return lists[0]
}
if n == 2 { //长度为2,直接调用两路归并算法,直接返回,其他情况递归调用
return mergeTwoLists(lists[0], lists[1])
}
//拆分为两个链表递归调用
mid := n / 2
l1 := mergeKLists(lists[:mid])
l2 := mergeKLi... |
package AlgoeDB
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"sync"
)
type Database struct {
config DatabaseConfig
mutex sync.Mutex
documents []map[string]interface{}
}
type DatabaseConfig struct {
Path string
SchemaValidator SchemaValidator
}
type SchemaValidator fun... |
/*
Input
None
Output
52 cards. No duplicates. Cards are represented as their unicode characters, e.g. 🂹.
The Unicode codepoints follow the following format:
The first three digits are 1F0.
The next digit is A, B, C, or D for spades, hearts, diamonds, and clubs respectively.
The next digit is 1 through... |
package types
import (
"github.com/irisnet/irishub/app/v1/auth"
sdk "github.com/irisnet/irishub/types"
)
type BankKeeper interface {
SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error)
AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.C... |
package main
import (
"encoding/json"
"fmt"
"github.com/urfave/cli"
"net"
"os"
)
func ls(_ *cli.Context) {
conn, err := net.Dial("tcp", configData.IP+":"+configData.PORT)
if err != nil {
fmt.Fprintf(os.Stdout, "Failed to connect to %v:%v because %v", configData.IP, configData.PORT, err)
}
defer conn.Close(... |
package main
import (
"archive/zip"
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/tealeg/xlsx"
"io"
"mime/multipart"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type _xlsx struct {
file multipart.File
fileHeader *multipart.FileHeader
date time.Time
isContainHe... |
package main
import "fmt"
func main() {
//array size is a part of its type
//init array populated with def values
var arr0 [3]int // [0,0,0]
fmt.Println("array arr0 short", arr0) // [0 0 0]
fmt.Printf("array arr0 short %v\n", arr0) // [0 0 0]
fmt.Printf("array arr0 full %#v\n", arr0) // [4]int{0, 0, 0}
//c... |
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
const (
nsPlayer = "player"
nsIAPI = "iapi"
nsProxy = "proxy"
nsLbrynet = "lbrynet"
nsUI = "ui"
nsLbrytv = "lbrytv"
LabelSource = "source"
LabelInstance = "ins... |
package clients
import (
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/7/23 9:13 上午
# @File : jz_45_扑克牌顺子.go
# @Description :
# @Attention :
*/
package offer
// 判断是否是连续的数字
func IsContinuous(numbers []int) bool {
// write code here
IsContinuousQSort(numbers, 0, len(numbers)-1)
last := 0
firstIndex:=-1
for index, v := range n... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package engine
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi"
"github.com/Azure/go-autorest/autorest/to"
)
func TestCreateUserA... |
package main
import (
"fmt"
"github.com/somehibs/tripapi/api"
)
func main() {
fmt.Println(tripapi.CacheTest()) // cache test
fmt.Println(tripapi.GetDrug("heroin")) // heroin itself
fmt.Println(tripapi.GetDrug("dex")) // dxm alias
fmt.Println(tripapi.GetDrug("butt")) // nonexistent
}
|
// Copyright 2021 BoCloud
//
// 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 wri... |
package main
import (
"archive/tar"
"bytes"
"context"
"io"
"io/ioutil"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/d... |
package engine
import (
"github.com/BurntSushi/toml"
"github.com/zhenghaoz/gorse/base"
"github.com/zhenghaoz/gorse/core"
"github.com/zhenghaoz/gorse/model"
"log"
"path"
)
// TomlConfig is the configuration for the engine.
type TomlConfig struct {
Server ServerConfig `toml:"server"`
Database DatabaseCon... |
package xxhash
import (
"hash/adler32"
"hash/crc32"
"hash/fnv"
"testing"
)
var (
in = []byte(`Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commo... |
package errs
import "errors"
var (
ErrInternalServerError = errors.New("err internal server error")
ErrEmptyBodyRequest = errors.New("err empty body request")
ErrAuth = errors.New("err auth")
ErrInvalidCountry = errors.New("err invalid country")
ErrInvalidUserID = errors.New("err inv... |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// vespa deploy command
// Author: bratseth
package cmd
import (
"fmt"
"io"
"log"
"strconv"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/vespa-engine/vespa/client/go/vespa"
)
func newDepl... |
package esm
import (
"../driver/elevio"
. "../config"
)
var extra_stop Order
var empty_order Order
//Hall order elevator queue
//Contains order with type (Up or Down) and floor
//A new order is pushed in the last position in the queue
var queue [N_floors * 2]Order
//Cab order elevator queue,
//List of 0's (no or... |
package core
import (
"image"
"os"
)
type Texture interface {
Value(u float64, v float64, point *Pt3) Col3
}
type SolidTexture struct {
Color Col3
}
type ImageTexture struct {
internalimg image.Image
}
func NewImageTexture(path string) *ImageTexture {
var reader, _ = os.Open(path)
var image, _, _ = image.De... |
package main
import "fmt"
type user struct {
name string
age byte
}
func main() {
u1 := user{"Tom", 12}
u2 := user{name: "Tom"}
fmt.Println(u1, u2)
}
|
package types
import (
"github.com/jinzhu/gorm"
// HOFSTADTER_START import
// HOFSTADTER_END import
)
/*
Name: AuthBasicUser
About: Basic Auth type
*/
// HOFSTADTER_START start
// HOFSTADTER_END start
/*
Where's your docs doc?!
*/
type AuthBasicUser struct {
/* ORM: server.api.databases.[name==pos... |
package 获取
var visibleNodeValues []int
func rightSideView(root *TreeNode) []int {
visibleNodeValues = make([]int, 0)
formVisibleNodeValues(root, 0)
return visibleNodeValues
}
func formVisibleNodeValues(root *TreeNode, nowLay int) {
if root == nil {
return
}
if nowLay == len(visibleNodeValues) {
visibleNode... |
package main
import (
"fmt"
"github.com/bosh-io/worker/src/worker/releases"
"log"
"os"
"strings"
)
func main() {
index, err := releases.LoadFile(os.Args[1])
if err != nil {
log.Panicf("loading index: %v", err)
}
orgs := index.GitHubOrgs()
fmt.Println(strings.Join(orgs, "\n"))
}
|
package middleware
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
)
func TestResponseEntry(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
request, _ := http.NewRequest(http.MethodG... |
package executor
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/wait"
... |
package opcua_client
import (
"fmt"
"reflect"
"testing"
"time"
"github.com/influxdata/telegraf/config"
"github.com/stretchr/testify/require"
)
type OPCTags struct {
Name string
Namespace string
IdentifierType string
Identifier string
DataType string
Want string
}
func ... |
package structs
import (
"WhereIsMyDriver/helper"
validator "gopkg.in/go-playground/validator.v9"
)
type (
// Response is standard response for http
Response struct {
Data interface{} `json:"data"`
Errors []string `json:"errors"`
}
)
// MapValidation mapping the validation of error
func MapValidation... |
package iirepo_stage_test
import (
"github.com/reiver/go-iirepo/stage"
"fmt"
)
func ExamplePath() {
var parent string = "/home/joeblow/workspaces/myproject"
repoStagePath := iirepo_stage.Path(parent)
fmt.Printf("The repo's stage directory's path is: %s\n", repoStagePath)
// Output:
// The repo's stage dir... |
package collectors_test
import (
"net/http"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"github.com/cloudfoundry-community/go-cfclient"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
. "github.com/bosh-prometheus/cf_exporter/colle... |
package controllers
import (
"fmt"
"net/http"
"BottleneckStudio/keepmotivat.in/app/session"
)
// TermsOfServiceController is the TermsOfService screen
func TermsOfServiceController() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "TermsOfService Controller")
flash :... |
package main
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/donkeyroll-shouting/valentinescards/pkg/constants"
"cloud.google.com/go/firestore"
"google.golang.org/api/option"
)
func NewFirestoreClient(ctx context.Context) (*firestore.Client, error) {
firestoreKeyPath := os.Getenv(constants.FIRE... |
package fileupload
import (
"errors"
"net/http"
"github.com/alejogs4/blog/src/post/domain/post"
"github.com/alejogs4/blog/src/shared/infraestructure/httputils"
)
func mapFileErrorToHttpError(err error) httputils.HttpError {
if errors.Is(err, post.ErrMissingPostPicture) {
return httputils.HttpError{Status: htt... |
package rhel85
import (
"fmt"
"path/filepath"
"sort"
"github.com/google/uuid"
"github.com/osbuild/osbuild-composer/internal/blueprint"
"github.com/osbuild/osbuild-composer/internal/crypt"
"github.com/osbuild/osbuild-composer/internal/disk"
osbuild "github.com/osbuild/osbuild-composer/internal/osbuild2"
"git... |
package termd_test
import (
"fmt"
"io/ioutil"
"github.com/tj/go-termd"
)
func Example() {
var c termd.Compiler
c.SyntaxHighlighter = termd.SyntaxTheme{
"keyword": termd.Style{},
"comment": termd.Style{
Color: "#323232",
},
"literal": termd.Style{
Color: "#555555",
},
"name": termd.Style{
C... |
// Used to show the landing page of the application
package archive
import (
"glsamaker/pkg/app/handler/authentication"
"glsamaker/pkg/app/handler/authentication/utils"
"glsamaker/pkg/database/connection"
"glsamaker/pkg/logger"
"glsamaker/pkg/models"
"net/http"
)
// Show renders a template to show the landing ... |
package main
import "fmt"
func main(){
var (
i float64= 20.4
a = 30
s = "Hye"
)
fmt.Println(i,s,a)
}
|
package sqlplugin
import (
"database/sql"
"go.temporal.io/server/common/primitives"
)
type (
// SignalsRequestedSetsRow represents a row in signals_requested_sets table
SignalsRequestedSetsRow struct {
ShardID int32
NamespaceID primitives.UUID
WorkflowID string
RunID primitives.UUID
SignalID... |
package managers
import (
"github.com/stretchr/testify/assert"
"testing"
)
const (
maxUint = ^uint(0)
maxInt = int(maxUint >> 1)
)
func TestNumbersManager_ToWords_English_OK(t *testing.T) {
var test = []struct {
Number int
Lang string
Expected string
}{
{-20, "en", "minus twenty"},
{15, "en", ... |
package main
// import (
// "fmt"
// )
/*
package main:每个 Go 文件都必须以 package name 语句开头。包(package)提供了代码封装和重用。这里包的名字为 main。
import "fmt":导入 fmt 包,在 main 函数中将使用这个包打印文本到标准输出。
func main():main函数是一个特殊的函数,它是 Go 程序的入口点。main 函数必须包含在 main package 中。 { 和 } 表示 main 函数的开始和结束。
*/
/*
语句 var age int 声明了一个类型为 int,名称为 age 的变量。... |
package beacon_test
import (
beacon "."
"reflect"
"testing"
)
func TestContainerEqual(t *testing.T) {
type Test struct {
A *beacon.Container
B *beacon.Container
Equal bool
}
tests := []Test{
{
A: &beacon.Container{
ID: "1234",
Service: "www",
Labels: map[string]string{
... |
package deferstats
import (
"database/sql"
"sync"
"time"
)
// deferDBList is used to keep a list of DeferDB objects
// and interact with them in a thread-safe manner
type deferDBList struct {
lock sync.RWMutex
list []DeferDB
}
// Add adds a DeferDB object to the list
func (d *deferDBList) Add(item DeferDB) {
d... |
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"os"
"strings"
"time"
)
func die(err error) {
warn(err)
os.Exit(1)
}
func warn(err error) {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
}
func main() {
if len(os.... |
// Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package common
// Common
const (
ErrCodeFail = iota
ErrCodeOk
ErrCodeHttp
ErrCodeSystem
ErrCodeNotFound
ErrCodeDuplicated
ErrCodeNoPermission
ErrCodeInvalidParams
ErrCodeInvalidVerifyCode
)
// Account
const (
ErrCodeWrongPassword = 1000 + iota
)
var ErrMessages = map[int]string{
ErrCodeFail: ... |
package main
import (
"fmt"
"os"
"strconv"
)
func fattoriale(n int) int {
if n > 0 {
n = n * fattoriale(n-1)
} else {
n += 1
}
return n
}
func main() {
n := os.Args[1]
nc, _ := strconv.Atoi(n)
fmt.Println("er fattoriale:", fattoriale(nc))
}
|
package minnow
import (
"bytes"
"testing"
)
func TestBytesToProperties(t *testing.T) {
propStr := "foo = bar\nbaz=2\nname = continue"
propBytes := bytes.NewBufferString(propStr).Bytes()
properties, err := BytesToProperties(propBytes)
if err != nil {
t.Errorf("Unexpected error: %s", err.Error())
}
if len(p... |
package fare
import (
"context"
"github.com/go-kit/kit/endpoint"
distancetypes "github.com/stamm/wheely/apis/distance/types"
"github.com/stamm/wheely/apis/fare/types"
)
func MakeCalculationEndpoint(svc IFareService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {... |
package main
import (
"fmt"
"io/ioutil"
"strings"
)
func readLines(path string) ([][]rune, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
lines := strings.Split(string(content), "\n")
rows := make([][]rune, len(lines))
for i, line := range lines {
rows[i] = []rune(line)... |
package server
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/Sirupsen/logrus"
"github.com/bryanl/dolb/service"
)
// PingRequest is a ping call from an agent.
type PingRequest struct {
AgentID string `json:"agent_id"`
ClusterID string `json:"cluster_id"`
ClusterName string `json:"cluster... |
package aiven
import (
"fmt"
"github.com/aiven/aiven-go-client"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func datasourceKafkaSchema() *schema.Resource {
return &schema.Resource{
Read: datasourceKafkaSchemaRead,
Schema: resourceSchemaAsDatasourceSchema(aivenKafkaSchemaSchema, "project", "s... |
package main
import (
"flag"
"fmt"
"time"
"strings"
"strconv"
"context"
"os/exec"
"bufio"
"bytes"
"gopkg.in/jabdr/monitoringplugin.v1"
)
type zpoolCommand interface {
ZpoolList(check *checkZFS, pool string) (output []byte, err error)
}
type linuxZpool struct {
}
func (lz *linuxZpool) ZpoolList(che... |
package main
import "fmt"
func main() {
fmt.Println(canVisitAllRooms([][]int{
{1},
{2},
{3},
{},
}))
fmt.Println(canVisitAllRooms([][]int{
{1, 3},
{3, 0, 1},
{2},
{0},
}))
}
func canVisitAllRooms(rooms [][]int) bool {
visit := make([]bool, len(rooms))
var dfs func(idx int)
dfs = func(idx i... |
package rtda
import (
rtc "jvmgo/jvm/rtda/class"
"jvmgo/util"
)
// todo: is there a better way to create String?
func NewJString(goStr string, clg rtc.ClassLoaderGetter) *rtc.Obj {
chars := util.StringToUtf16(goStr)
internedStr := getInternedString(chars)
if internedStr != nil {
return internedStr
}
classLo... |
package full_test
import (
"testing"
"github.com/mkamadeus/cipher/cipher/vigenere/full"
)
func TestDecryptt(t *testing.T) {
cipher := "DPYFNWKHRDCABKO"
key := "sony"
expected := "THISISPLAINTEXT"
decrypted := full.Decrypt(cipher, key)
if decrypted != expected {
t.Fatalf("full vignere Decryption failed, exp... |
package main
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
proto "github.com/golang/protobuf/proto"
"github.com/jhump/protoreflect/dynamic"
"github.com/jhump/protoreflect/grpcreflect"
"golang.org/x/net/http2"
"google.golang.org/grpc"
rpb "google.golang... |
package cloudconfig
import "github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
// templateData is a composed data type that adds encrypter type info to
// AWSConfigSpec.
type templateData struct {
v1alpha1.AWSConfigSpec
EncrypterType string
VaultAddress string
EncryptionKey string
}
|
package oauth2
import (
"context"
"net/http"
)
// the request parameters in OAuth request methods
type RequestWapper struct {
// access_token
GrantType GrantType
ClientId string
ClientSecret string
// AuthorizationCode
RedirectUri string
Code string
// Proof Key
CodeVerifier string
Co... |
// Copyright 2017 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 frame
import (
"fmt"
"strings"
"sync"
"github.com/k0kubun/go-ansi"
)
var (
lockSync sync.Once
screenLock *sync.Mutex
)
func newScreenEvent(line *Line) *ScreenEvent {
e := &ScreenEvent{
row: line.row,
value: make([]byte, len(line.buffer)),
}
copy(e.value, line.buffer)
return e
}
// TODO: t... |
package models
import "go.mongodb.org/mongo-driver/bson/primitive"
type CookieResponse struct {
CodeAuth string `json:"codeAuth,omitempty"`
ID primitive.ObjectID `json:"_id,omitempty"`
}
|
/**
* day 10 2020
* https://adventofcode.com/2020/day/10
*
* compile: go build main.go
* run: ./main < input
* compile & run: go run main.go < input
**/
package main
import (
"fmt"
"bufio"
"strings"
"os"
"sort"
)
func jolts(adapters []int) int {
ones := 0
threes := 0
joltDiff := 0
prevAdapter := ... |
//go:generate go run generate.go mergesort.go
//go:generate goimports -w ../../mergesort/
//go:generate gofmt -w ../../mergesort/
package main
const PACKAGE = "mergesort"
const TEMPLATE = `
// {{.FuncName}} sorting slice of {{.Name}}
func {{.FuncName}}(in []{{.Name}}) []{{.Name}} {
if len(in) <= 1 {
return... |
package _go
type ListNode1 struct {
Val int
Next *ListNode1
}
func addTwoNumbers(l1 *ListNode1, l2 *ListNode1) *ListNode1 {
dummyHead := &ListNode1{Val: 0}
n1, n2, carry, cur := 0, 0, 0, dummyHead
for l1 != nil || l2 != nil || carry != 0 {
if l1 == nil {
n1 = 0
} else {
n1 = l1.Val
l1 = l1.Next
... |
package backup
import (
"errors"
"io"
"os"
"github.com/mholt/archiver/v3"
"github.com/pterodactyl/wings/system"
)
type LocalBackup struct {
Backup
}
var _ BackupInterface = (*LocalBackup)(nil)
func NewLocal(uuid string, ignore string) *LocalBackup {
return &LocalBackup{
Backup{
Uuid: uuid,
Ignore... |
package main
import (
"bytes"
"math/big"
weak "math/rand"
"testing"
"time"
)
func init() { weak.Seed(time.Now().UnixNano()) }
func TestRSACryptPKCS1v15(t *testing.T) {
const (
exponent = 3
bits = 256
)
buf := make([]byte, 16)
for i := 0; i < 5; i++ {
priv, err := RSAGenerateKey(exponent, bits)
i... |
package bbir
import (
"context"
. "github.com/vvatanabe/go-backlog/backlog/v2"
)
type BacklogAPIClientAsMock struct {
addIssue func(ctx context.Context, projectID ProjectID, summary string, issueTypeID IssueTypeID, priorityID PriorityID, opt *AddIssueOptions) (*Issue, error)
getIssue func(ctx conte... |
package main
import (
//"bytes"
"database/sql"
"flag"
"fmt"
"net/http"
"os"
//"regexp"
//"strconv"
//"strings"
"time"
"math"
_ "github.com/lib/pq"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/log"
"strconv"
)
var (
listenAddress = flag.String(
"web.listen-address", ":9113... |
package csvConvert
import (
"encoding/csv"
"log"
"os"
"strings"
)
// OpenCSV read file csv and return slice of string
func OpenCSV(file string) ([]string, error) {
// open file
csvFile, err := os.Open(file)
if err != nil {
panic(err)
}
defer func(csvFile *os.File) {
err := csvFile.Close()
if err != nil... |
/*
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 datamodel
import (
"fmt"
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/modules/db"
form2 "github.com/GoAdminGroup/go-admin/plugins/admin/modules/form"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
"github.com/GoAdminGroup/go-admin/template"
"github.com/Go... |
package components
import (
"github.com/GoAdminGroup/go-admin/template/types"
"html/template"
)
type ColAttribute struct {
Name string
Content template.HTML
Size string
types.Attribute
}
// 盢把计砞竚ColAttribute(struct)
func (compo *ColAttribute) SetContent(value template.HTML) types.ColAttribute {
compo.C... |
// Package space helps remove unnecessary spaces in byte slice
package space
import "unicode"
func Brush(input []byte) []byte {
i := 0
seenSpace := false
for _, b := range input {
if unicode.IsSpace(rune(b)) {
if seenSpace {
continue
}
b = ' '
seenSpace = true
} else {
seenSpace = false
}
... |
package handler
import (
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
"github.com/GoGroup/Movie-and-events/booking"
"github.com/GoGroup/Movie-and-events/flash"
"github.com/GoGroup/Movie-and-events/user"
"github.com/GoGroup/Movie-and-events/comment"
"github.com/GoGroup/Movie-and-events/controller"
... |
package discovery
import (
"context"
"sync"
"testing"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore"
cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
swarmt "gx/ipfs/QmTJCJaS8Cpj... |
package main
import (
"github.com/garyburd/redigo/redis"
"time"
"strings"
// "fmt"
)
const (
cacheResultPre = "atat:cache:result:"
cacheInstancePre = "atat:cache:instance:"
cacheResultSort = "atat:index:_score_:*"
cacheResultTime = 3600
)
// redispool *redis.Pool
type RDB struct {
redispool *redis.Pool
}
... |
package rsd
import (
"errors"
"fmt"
"strings"
"github.com/cuigh/auxo/app"
)
// definitionV1 V1 版本服务定义
type definitionV1 struct {
JavaPackage string `xml:"javaPackage,attr"`
Version string `xml:"version,attr"`
Service *struct {
Name string `xml:"name,attr"`
Alias string `xml:"ali... |
package beatmanage
import (
"fmt"
"net/http"
"net/url"
"runtime"
)
func Regist(key, user, version, tag, port string) {
params := url.Values{}
params.Set("uuidKey", key)
params.Set("agentVersion", version)
params.Set("tag", tag)
params.Set("system", runtime.GOOS)
params.Set("kernelVersion", runtime.GOARCH)... |
package gedcom
// ChildNode is the natural, adopted, or sealed (LDS) child of a father and a
// mother.
type ChildNode struct {
*SimpleNode
family *FamilyNode
}
func newChildNode(family *FamilyNode, value string, children ...Node) *ChildNode {
return &ChildNode{
newSimpleNode(TagChild, value, "", children...),
... |
package main
import (
"github.com/gorilla/securecookie"
"net/http"
)
var (
// Generated by securecookie.GenerateRandomKey(64) and (32)
hashKey = []byte{144, 70, 174, 35, 6, 213, 43, 118, 83, 230, 186, 64, 107, 144, 8, 112, 176, 2, 0, 88, 81, 226, 52, 100, 242, 56, 45, 57, 221, 60, 129, 68, 63, 214, 63, 85, 59, 2... |
package scatterGatherPattern
import (
"design-patterns-go/scatterGatherPattern/processor"
"fmt"
)
type ScatterGather interface {
Run()
}
type scatterGather struct {
scatterGather ScatterGather
processors []processor.Processor
results chan string
}
func NewScatterGather() scatterGather {
return scatterGather{... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func ReadData(fname string) (tiles []*Tile) {
f, err := os.Open(fname)
if err != nil {
log.Fatalf("Error opening dataset '%s': %s", fname, err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
var currentTile s... |
//Cannot nest block comments
/* Start of comment
/*nested comment */
end of comment*/ |
package model
import (
"sync"
"errors"
)
var (
sLock sync.Mutex
ErrBookNotExist = errors.New("the book is not exist")
ErrBookNumWrong = errors.New("the deleted book num is wrong")
)
type Student struct {
Name string
Grade string
Id string
Sex string
//指针存的结构小
books []*BorrowItem
}
type BorrowItem struct ... |
package container
import (
"fmt"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/terassyi/mycon/pkg/spec"
)
type Config struct {
Id string
Bundle string
Spec *specs.Spec
}
func NewConfig(id string, bundle string) (*Config, error) {
s, err := spec.LoadSpec(bundle)
if err != nil {
return ... |
package utils
import (
"container/list"
"math"
)
type DataAdapter struct {
Data interface{}
}
func (d DataAdapter) ToString() string {
return d.Data.(string)
}
func (d DataAdapter) ToFloat() float64 {
var returnData = math.MaxFloat64
returnData = d.Data.(float64)
return returnData
}
func (d DataAdapter) To... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//749. Contain Virus
//A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
//The world is modeled as a ... |
package rest
import (
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/kataras/iris/v12"
)
// SetSecureEmailRequest 设置安全邮箱请求
type SetSecureEmailRequest struct {
Email string `json:"email"` // 邮箱
Serial... |
package data
import (
"fmt"
"github.com/stretchr/testify/require"
"net/url"
"strings"
"testing"
"time"
)
func TestBuildUrl_WithZeroHours_ReturnsNow(test *testing.T) {
hours := 0
location := ""
crimeType := ""
resultUrl,_ := buildUrl(hours, location, crimeType)
now := time.Now()
nowStr := fmt.Sprintf("%d... |
package minstack
import "fmt"
// 155. 最小栈:设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
type MinStack struct {
// 栈顶指针
top int
// 存放元素
data []int
// 存放当前栈中的最小值
min []int
}
func (s *MinStack) String() string {
if len(s.data) == 0 {
return "nothing"
}
return fmt.Sprint("Stack: ", s.data, "top")
}
/** initializ... |
/*
Copyright 2015 Google Inc. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
*/
// Package gcp is the Google Cloud Print API client.
package gcp
import (
"bytes"
"encoding/json"
"err... |
package rest
import (
"context"
"encoding/json"
"log"
"net/http"
)
// ErrorResponse represents a response containing an error message.
type ErrorResponse struct {
StatusCode int `json:"statusCode"`
Error string `json:"error"`
}
// generic error handler for REST API
func renderErrorResponse(ctx context.... |
package main
import "fmt"
// func test(x int) int {
// if x == 1 {
// return 1
// } else {
// return x * test(x-1)
// }
// }
// func main() {
// fmt.Println(test(5))
// }
//}
func test(x int) int {
if x == 1 {
return 1
} else if x == 2 {
return 2
} else {
return test(x-1) + test(x-2)
}
}
func main... |
package parser
import (
"github.com/stretchr/testify/assert"
"testing"
)
func testNewParser(t *testing.T) {
p, err := NewParser("test.json", nil)
assert.NotNil(t, err)
assert.Nil(t, p)
}
func TestParseLineOK(t *testing.T) {
p := &RawLogParser{}
l, err := p.Parse("2013-10-23T10:12:35.298Z 2013-10-23T10:12:35.3... |
package day5
import (
"testing"
"github.com/achakravarty/30daysofgo/assert"
)
type multiple struct {
index int
multiple int
}
type testCase struct {
num int
index int
multiples []multiple
}
var testCases = []testCase{
testCase{num: 2, multiples: []multiple{
multiple{index: 1, multiple: 2},
... |
package Solution
type ListNode struct {
Val int
Next *ListNode
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func Solution(head *ListNode) *TreeNode {
if head == nil { return nil }
if head.Next == nil { return&TreeNode{Val: head.Val} }
slow, fast := head, head
var prev *ListN... |
package xdriver
import (
"fmt"
"image"
"image/draw"
"log"
"os"
"runtime"
"sync"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/shm"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil/xcursor"
"github.com/jmigpin/editor/driver/xdriver/copypaste"
"github.com/jmigpin/editor/driver/xdr... |
package main
import (
"net/http"
"net"
)
func RemoteIp(r *http.Request) string {
remoteAddr := r.RemoteAddr
if ip := r.Header.Get("X-Real-IP"); ip != "" {
remoteAddr = ip
} else if ip = r.Header.Get("X-Forwarded-For"); ip != "" {
remoteAddr = ip
} else {
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
}... |
package grok
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strconv"
"time"
"cloud.google.com/go/pubsub"
"github.com/sirupsen/logrus"
)
// PubSubSubscriber ...
type PubSubSubscriber struct {
client *pubsub.Client
handler func(interface{}) error
subscriberID s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.