text stringlengths 11 4.05M |
|---|
package main
import (
"github.com/garyburd/redigo/redis"
)
var (
RedisAddr = ":6379"
keyspacePrefix = "__keyspace@0__:"
workerKeyPrefix = "test/"
)
func NewConn() (redis.Conn, error) {
return redis.Dial("tcp", RedisAddr)
}
|
package main
import(
"fmt"
)
func search(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
left := 0
right := len(nums) - 1
mid := -1
for ;left<=right; {
mid = left + (right + 1 - left) /2
if nums[mid] == target {
return mid
}
if nums[left] <= nums[mid] {
if nums[left] <= tar... |
package main
import (
"./models"
"database/sql"
"flag"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
var (
schemaFilePath string
driver string
dbUser string
dbPwd string
dbHost string
dbPort int
drop = true
operation string
)
func init() {
fla... |
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(generate(12, "気温", 22.4))
}
func generate(x int, y string, z float64) string {
xs := strconv.Itoa(x)
zs := strconv.FormatFloat(z, 'f', 1, 64)
return xs + "時の" + y + "は" + zs
}
|
//
// Copyright 2020 The AVFS 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 ag... |
package parser
import "fmt"
// SourceFile represents a source file
type SourceFile struct {
Name string
Src []rune
}
// Cursor represents a source-code location
type Cursor struct {
Index uint
Column uint
Line uint
File *SourceFile
}
// NewCursor creates a new cursor location based on the given source f... |
package iotdatahandler
import (
"github.com/gravitational/trace"
"github.com/jinzhu/gorm"
)
//IotDataHandlerDB is the main struct
type IotDataHandlerDB struct {
dbconn *gorm.DB
tableName string
}
//GetNewIotDataHandlerDB returns a new IotDataHandlerDB
func GetNewIotDataHandlerDB(db *gorm.DB) *IotDataHandlerDB... |
// 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 sort
import (
"fmt"
"testing"
)
func TestInsertionSort(t *testing.T) {
arr := []int{5, 7, 2, 5, 6, 8, 4, 13, 5, 6, 7}
InsertionSort(&arr)
fmt.Println(arr)
} |
package textutils
import (
"bufio"
"io"
)
type NgramIterator struct {
s *bufio.Scanner
minN int
maxN int
currGrams [][]byte
currMaxN int
currN int
filter func([]byte) bool
}
func NewNgramIterator(r io.Reader, minN, maxN int) *NgramIterator {
if minN <= 0 {
minN = 1
}
if minN > maxN {
maxN ... |
// -----------------------------------------------------------------------------
// Coordinator package used for defining queue listener and event aggregator.
// -----------------------------------------------------------------------------
package coordinator
import (
"bytes"
"encoding/gob"
"godistributed-rabbitmq/... |
package registry
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewRepoConfig(t *testing.T) {
dir, err := os.MkdirTemp("", "feature_repo_*")
assert.Nil(t, err)
defer func() {
assert.Nil(t, os.RemoveAll(dir))
}()
filePath := filepath.Join(dir, "feature_store.yaml")
... |
package core
import (
"time"
"github.com/cbergoon/merkletree"
)
type Block struct {
Index int64
CreationTime time.Time
CommitTime time.Time
Transactions merkletree.MerkleTree
}
func NewBlock() *Block {
b := &Block{}
return b
}
func (b *Block) GenerateGenesis() {
}
func (b *Block) Generate() {
}... |
package config
type Parameter interface {
}
|
package main
import (
"strings"
"github.com/corymurphy/adventofcode/shared"
)
type Commands []Command
func NewCommands(input []string) *Commands {
commands := Commands{}
for _, row := range input {
if row == "" {
continue
}
commands = append(commands, *NewCommand(row))
}
return &commands
}
type Com... |
/*
Shared memory allocator. Currently we're just allocating memory on a fixed
"heap", no free.
*/
package main
import (
"github.com/apache/arrow/go/arrow/memory"
)
const (
memAlign = 64
)
var (
// Make sure ShmAllocator implements memory.Allocator
_ memory.Allocator = &ShmAllocator{}
)
// ShmAllocator is a shar... |
package main
import (
"fmt"
)
var a string
//---------------
var (
c string
d int
)
//---------------
var e string = "3. 變數同時宣告並賦值"
//-----------------
func main() {
a = "1. 宣告一個變數並賦值"
fmt.Println(a)
var b int //變數宣告可於func外或者func內
b = 1
fmt.Println(b)
//---------------
c = "2. 一次宣告多筆變數並賦值 "
d = 0
fmt.Pr... |
package email
import (
"gopkg.in/gomail.v2"
)
func SendEmail(content,email string)error{
d := gomail.NewDialer("smtp.163.com",25,"y484742285@163.com","YMZDBQFXSWIRXSQR")
//YMZDBQFXSWIRXSQR
m := gomail.NewMessage()
m.SetAddressHeader("From","y484742285@163.com","yinqingping")
m.SetHeader("To",email)
m.SetHeader... |
package v1
import (
"context"
v2beta2 "k8s.io/api/autoscaling/v2beta2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
type HorizontalPodAutoScalersGetter interface {
Deployment(namespace string) HorizontalPodAutoScalersInterface
}
type HorizontalPodAutoScalersInterface interface {... |
// Copyright 2020-present Kuei-chun Chen. All rights reserved.
package keyhole
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/simagix/gox"
"github.com/simagix/keyhole/mdb"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/x/m... |
package pkg3
import (
"fmt"
)
var (
_ = constInitCheck()
_ = variableInit("v1")
_ = variableInit("v2")
)
const (
c1 = "c1"
c2 = "c2"
)
func constInitCheck() string {
if c1 != "" {
fmt.Println("pkg3: const c1 has been initialized")
}
if c2 != "" {
fmt.Println("pkg3: const c2 has been initialized")
}
r... |
package main
import "fmt"
func isRepetitive(slice []int) bool {
for i := 1; i < len(slice); i++ {
if slice[i] != slice[0] {
return false
}
}
return true
}
func msBits(slice []int, sliceElement int) int {
max,min := slice[0], slice[0]
for i:=0;i<len(slice);i++ {
if slice[i] > max {
max = slice[i]
}... |
/*
create a func with the identifier foo that returns an int
create a func with the identifier bar that returns an int and a string
call both funcs
print out their results
*/
package main
import "fmt"
func foo() int {
return 2
}
func bar() (int, string) {
return 42, "The answer for everthing"
}
func main() {
fm... |
package main
// Generated code
var creditsB64 = "MjBrZGMvQ0NVcGRhdGVyVUkgJiBDb21wbGlhbmNlCnRoZSBwcm9ncmFtIGl0c2VsZgp+IX4KCk1JVCBMaWNlbnNlCgpDb3B5cmlnaHQgKGMpIDIwMTkgQ0NEaXJlY3RMaW5rCgpQZXJtaXNzaW9uIGlzIGhlcmVieSBncmFudGVkLCBmcmVlIG9mIGNoYXJnZSwgdG8gYW55IHBlcnNvbiBvYnRhaW5pbmcgYSBjb3B5Cm9mIHRoaXMgc29mdHdhcmUgYW5kIGFzc29... |
package scrape
import (
"encoding/json"
"fmt"
"log"
)
// Print the JSON data
func (s *Scrape) PPrint() {
b, err := json.MarshalIndent(s.Events, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", b)
}
|
package svc
import (
"bookstore/rpc/add/internal/config"
"bookstore/rpc/model"
"github.com/tal-tech/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
c config.Config
Model *model.BookModel
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
c: c,
Mode... |
package main
import (
"fmt"
"crypto/hmac"
"crypto/sha256"
"io"
)
func main() {
a:=getcode("example")
fmt.Println(a)
b:=getcode("example1")
fmt.Println(b)
}
func getcode(str string) string{
h:=hmac.New(sha256.New,[]byte("passkey"))
io.WriteString(h,str) //write our string into the hash
retur... |
package main
import (
"fmt"
"regexp"
"io/ioutil"
"io"
"os"
)
//error checking function
func check(e error) {
if e != nil{
panic(e)
}
}
//function to open file and read the contents and get file name for wrtie file
func read() (string, []byte) {
//gets input file and output file name by command li... |
/*
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, so... |
package iot
// Cloud is the interface of IOT clound
type Cloud interface {
Push(v *Value) error
}
// Value ...
type Value struct {
Device string
Value interface{}
}
// NewCloud ...
func NewCloud(config interface{}) Cloud {
var cloud Cloud
switch config.(type) {
case *WsnConfig:
cfg := config.(*WsnConfig)
... |
package setup
import (
"log"
"strings"
"io/ioutil"
"os"
"fmt"
"path/filepath"
"strconv"
)
func reportNeedOfChanges(name string) {
fmt.Println("\n\nStart searching for change needs!")
rootPath := fmt.Sprintf("%s/", getConsumerName(name))
filepath.Walk(rootPath, needChange)
fmt.Println("\n\nFinished searc... |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package feedback
import (
"encoding/hex"
"fmt"
"log"
"github.com/golang/dep/gps"
)
const (
// ConsTypeConstraint represents a constraint
ConsTypeConstr... |
package transformer
import (
"github.com/confluentinc/confluent-kafka-go/kafka"
)
type passThrough struct{}
// Transform a kafka Message
func (p passThrough) Transform(src *kafka.Message) []*kafka.Message {
topic := *src.TopicPartition.Topic + "-passthrough"
msg := &kafka.Message{
TopicPartition: kafka.TopicPa... |
package main
func Min(a, b int) int {
if a < b {
return a
}
return b
}
func Max(a, b int) int {
if a > b {
return a
}
return b
}
func maxArea(height []int) int {
maxArea := 0
var left, right = 0, len(height) - 1
for left < right {
area := Min(height[left], height[right]) * (right - left)
maxArea = M... |
package main
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"unicode"
"github.com/sirupsen/logrus"
"github.com/viert/go-lame"
)
const (
audioBitRate = 123
streamApiUrl = "http://youtube.com/get_video_info?video_id="
)
type stream map[... |
package main
import "testing"
func TestCalcFuel(t *testing.T) {
s := CalcFuel(14)
if s != 2 {
t.Errorf("CalcFuel(14) should be 2, got %v: ", s)
}
s = CalcFuelRecur(14, 0)
if s != 2 {
t.Errorf("CalcFuelRecur(14) should be 2, got %v: ", s)
}
s = CalcFuel(1969)
if s != 966 {
t.Errorf("CalcFuel(1969) shou... |
package api
import (
"GinPractice/users"
"fmt"
"github.com/gin-gonic/gin"
)
// Login 是用来处理登陆操作的func
func Login(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
if username == "" {
fmt.Print("后台消息“不存在的用户要登陆")
}
fmt.Print(username)
fmt.Print(password)
success, err := u... |
package _606_Construct_String_from_Binary_Tree
import (
"testing"
)
type testCase struct {
input *TreeNode
output string
}
func TestTree2str(t *testing.T) {
cases := []testCase{
{
input: &TreeNode{Val: 1, Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 4}}, Right: &TreeNode{Val: 3}},
output: "1(2(4))(3)",... |
package models
type IPLocation struct {
// The right side is the name of the JSON variable
Ip string `json:"ip,omitempty"`
CountryCode string `json:"country_code,omitempty"`
CountryName string `json:"country_name,omitempty"`
RegionCode string `json:"region_code,omitempty"`
RegionName string `json... |
package gradients
import (
"image/color"
"math"
"math/rand"
"github.com/devinmcgloin/clr/clr"
"github.com/devinmcgloin/sail/pkg/slog"
"github.com/fogleman/gg"
)
// Skyspace defines the type of the sketch
type Skyspace struct {
}
// Dimensions determines how large it should be
func (ss Skyspace) Dimensions() (... |
package bitset
// the uint64Size of a bit set
const uint64Size = uint(64)
// log2Uint64Size is lg(uint64Size)
const log2Uint64Size = uint(6)
// BitSet efficient and fast set of bits.
type BitSet struct {
length uint
set []uint64
}
// New creates a new BitSet with specified length.
func New(length uint) *BitSet... |
/*
A distributed block-chain transactional key-value service
Assignment 7 of UBC CS 416 2016 W2
http://www.cs.ubc.ca/~bestchai/teaching/cs416_2016w2/assign7/index.html
Created by Harlan Sim and Sean Blair, April 2017
This package specifies the application's interface to the key-value
service library.
*/
package k... |
package defaults
import "github.com/openshift/installer/pkg/types/external"
// SetPlatformDefaults sets the defaults for the platform.
func SetPlatformDefaults(p *external.Platform) {
p.PlatformName = "Unknown"
}
|
package light
import (
"testing"
"github.com/calbim/ray-tracer/src/color"
"github.com/calbim/ray-tracer/src/tuple"
)
func TestPointLight(t *testing.T) {
intensity := color.New(1, 1, 1)
position := tuple.Point(0, 0, 0)
pointLight := PointLight(position, intensity)
if pointLight.Intensity != intensity || pointL... |
/*
Copyright 2021 The Kubernetes 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, ... |
/*
I want format a JSON string into human-readable form. A string like this:
'{"foo":"hello","bar":"world","c":[1,55,"bye"]}'
would be formatted as:
{
"foo": "hello",
"bar": "world",
"c": [
1,
55,
"bye"
]
}
Rules:
For objects and arrays properties and items should be starting in new line w... |
package localcache
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/repository"
"github.com/andywow/golang-lessons/lesson-calendar/pkg/eventapi"
)
func createTestEvent(t *testing... |
package main
import "fmt"
// func keywork | [receiver] | <func name> | [return] | ([params]) | { //code }
func main() {
fmt.Println("Hello World!")
}
// main is the entry point to your program
|
package main
import (
"fmt"
"github.com/ClarityServices/skynet2"
"github.com/ClarityServices/skynet2/daemon"
"github.com/ClarityServices/skynet2/log"
"github.com/kballard/go-shellquote"
"os"
"sync"
"text/template"
)
var startTemplate = template.Must(template.New("").Parse(
`Started service with UUID {{.UUID}... |
// Copyright 2019 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 concurrency provides common concurrency patterns and utilities.
package concurrency
import "github.com/pkg/errors"
// Runnable describes something which can start and stop.
type Runnable interface {
Start() error
Stop()
}
// AsyncRunnable is a runnable which is can run asynchrounously
type AsyncRunnable... |
package testutil
import (
"database/sql"
"testing"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
func OpenDBForTest(t *testing.T) *sqlx.DB {
t.Helper()
db, err := sql.Open(
"mysql",
"todo:todo@tcp(127.0.0.1:33306)/todo?parseTime=true",
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(fun... |
package ca
import (
"regexp"
"strings"
"github.com/rightscale/rsc/ca/cac"
"github.com/rightscale/rsc/cmd"
"github.com/rightscale/rsc/metadata"
"github.com/rightscale/rsc/rsapi"
)
// Metadata synthetized from all CA APIs metadata; setup once
var GenMetadata = setupMetadata()
// API is the CA 1.0 common client ... |
package orm
import (
//"GoldenTimes-web/models"
//"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
func Insert(i interface{}) (int64, error) {
o := orm.NewOrm()
num, err := o.Insert(i)
return num, err
}
|
package test_driver
import (
"github.com/netapp/netappdvp/storage_drivers"
log "github.com/Sirupsen/logrus"
)
type FakeStorageDriverConfig struct {
storage_drivers.CommonStorageDriverConfig // embedded types replicate all fields
ManagementLIF string `json:"managementLIF"`
DataLIF ... |
package cmd
import (
"MyCart/cmd/Services"
"github.com/spf13/cobra"
)
var addProductsToCatlogCmd = &cobra.Command{
Use: "addProductsToCatlog",
Short: "You can view all the categories for shopping",
Long: `You can view all the categories for shopping`,
RunE: func(cmd *cobra.Command, args []string) error {
... |
package payment
import (
"fmt"
)
type Cash struct {
}
func CreateCashAccount() *Cash {
return &Cash{}
}
func (c Cash) ProcessPayment(amount float32) bool {
fmt.Println("Processing a cash transaction...")
return true
}
|
package http
import (
prox "github.com/davepgreene/slackmac/proxy"
log "github.com/sirupsen/logrus"
"github.com/vulcand/oxy/stream"
"net/http"
)
func proxy(url string) http.Handler {
proxy := prox.New(url)
s, err := stream.New(proxy)
if err != nil {
log.Fatal(err)
}
return s
}
|
/*
Copyright 2020 SUSE
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, s... |
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"simpleDateParser"
"syscall"
)
func main(){
var (
httpAddr = flag.String("http",":8080","http port to listen on")
)
flag.Parse()
ctx := context.Background()
// our simpleDateParser service
srv := simpleDateParser.NewServic... |
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
channel := make(chan int)
for i := 0; i < 5; i++ {
canal := "Canal-" + strconv.Itoa(i)
go worker(channel, canal)
}
for i := 0; i < 25; i++ {
channel <- i
}
}
func worker(channel chan int, canal string) {
for i := range channel {
fmt.Pr... |
package XMLParsers
import (
"encoding/xml"
"WorkingPromo/Utils"
)
//Главный хмл по предложениям по секции который мы получаем
//что то возможно проигнорировал, сейчас не вспомню
type OffersXML struct {
XMLName xml.Name `xml:"digiseller.response"`
Retval string `xml:"retval"`
RetDesc stri... |
package Utils
import (
"math/rand"
)
func Delete(array []int, index int) []int{
a := array
a = append(a[:index], a[index+1:]...)
return a
}
func GenArray(len int) []int{
var Sorted_Array = make([]int, len)
for i:= 0; i < len; i++{
Sorted_Array[i] = i+1
}
var Unsorted_Array = make([]int, 0)
for i:= 0; i... |
package ctx
import (
"net/http"
)
type ctxKeyUserID struct{}
// GetUserID reads userId from context
func GetUserID(r *http.Request) string {
// check context
if id, ok := getStr(ctxKeyUserID{}, r); ok {
return id
}
// no id
return ""
}
// SetUserID stores userID in context
func SetUserID(id string, r *http.... |
package suite_init
import (
"fmt"
"os"
"path/filepath"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
. "github.com/onsi/gomega"
"github.com/werf/werf/integration/pkg/utils"
)
type TmpDirData struct {
TmpDir string
TestDirPath string
}
func NewTmpDirData() *TmpDirData {
data := &TmpDirData{}
Set... |
package manager
import (
"github.com/golang/glog"
"sub_account_service/finance/db"
)
func InitAutoTB() {
if db.AutoMigrate == true {
glog.Infoln("init AutoMigrate mysql db tables")
}
}
|
package xml
import (
"bufio"
"fmt"
"sync"
)
var endPool = sync.Pool{
New: func() interface{} {
return new(EndElement)
},
}
// releaseEnd returns an EndElement to the pool.
func releaseEnd(end *EndElement) {
//end.Reset()
endPool.Put(end)
}
// EndElement represents a XML end element.
type EndElement struct ... |
package platform
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"image"
"io"
"io/ioutil"
"log"
"os"
"time"
"github.com/jcorbin/anansi"
"github.com/jcorbin/anansi/ansi"
)
var (
errReplayDone = errors.New("replay done")
errReplayStop = errors.New("replay stop")
)
type replay struct {
cereal []byte
... |
package neatly
import (
"bytes"
"compress/gzip"
"crypto/md5"
"encoding/json"
"fmt"
"github.com/gomarkdown/markdown"
"github.com/klauspost/pgzip"
"github.com/viant/toolbox"
"github.com/viant/toolbox/data"
"github.com/viant/toolbox/data/udf"
"github.com/viant/toolbox/storage"
"github.com/viant/toolbox/url"
... |
package event
import (
v1 "k8s.io/api/core/v1"
kscheme "k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/record"
"k8s.io/klog"
"github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/clientset/versioned/scheme"
)
const componen... |
package socks
import "strings"
const UNKNOWN = "unknown"
type version byte
// SOCKS versions.
const (
SOCKS4 = version(0x04)
SOCKS5 = version(0x05)
)
func (v version) String() string {
switch v {
case SOCKS4:
return "SOCKS4/4a"
case SOCKS5:
return "SOCKS5"
}
return ""
}
func (v version) LabelValue() st... |
package 链表
func deleteNode(head *ListNode, val int) *ListNode {
dummyHead := &ListNode{Next: head}
cur := dummyHead
for cur.Next != nil {
if cur.Next.Val == val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return dummyHead.Next
}
/*
题目链接: https://leetcode-cn.com/problems/shan-chu-lian-biao... |
package intercom
type TestHTTPClient struct{}
func (h TestHTTPClient) Get(uri string, queryParams interface{}) ([]byte, error) { return nil, nil }
func (h TestHTTPClient) Post(uri string, body interface{}) ([]byte, error) { return nil, nil }
func (h TestHTTPClient) Patch(uri string, body interface{}) ([]byte, e... |
package main
import (
"fmt"
"net/http"
)
func main() {
resp, err := http.Head("https://xueyuanjun.com")
if err != nil {
fmt.Println("fail", err.Error())
return
}
defer resp.Body.Close()
for key, value := range resp.Header {
fmt.Println(key, ":", value)
}
} |
package object
import (
"time"
)
type ArticleThumbsUpMapping struct {
Id int `gorm:"primary_key"`
CreatedAt time.Time
UserId int `form:"userid"`
ArticleId int `form:"articleid"`
}
|
package callback
import (
"context"
"fmt"
"strings"
"github.com/cloudreve/Cloudreve/v3/pkg/filesystem"
"github.com/cloudreve/Cloudreve/v3/pkg/filesystem/driver/cos"
"github.com/cloudreve/Cloudreve/v3/pkg/filesystem/driver/local"
"github.com/cloudreve/Cloudreve/v3/pkg/filesystem/driver/onedrive"
"github.com/cl... |
package day7
import (
"strconv"
"strings"
"github.com/littleajax/adventofcode/helpers"
)
//Build a distributed graph
//Going the other direction now, not parents, but children, with multiplicative counts
func ShinyGoldBagChildren(shinyGold *BagWithChildren) (totalChildren int) {
for _, child := range shinyGold.c... |
package main
import "github.com/codegangsta/cli"
var Commands = []cli.Command {
commandVolume,
commandImage,
commandNetwork,
}
var commandVolume = cli.Command {
Name: "volume",
ShortName: "v",
Usage: "Removed orphaned volumes from the host",
Action: doVolumes,
Flags: []cli.Flag {
cli.BoolFlag {
Name: "f... |
package main
import (
"context"
"flag"
"github.com/samkreter/go-core/example/services/frontend"
"github.com/samkreter/go-core/log"
"github.com/samkreter/go-core/trace"
"github.com/sirupsen/logrus"
)
const (
frontendAddr = ":8081"
customerAddr = "customers:8082"
serviceName = "frontend"
)
func main() {
lo... |
package ipfs
import (
"fmt"
// "os"
"testing"
// shell "github.com/ipfs/go-ipfs-api"
)
func Test(t *testing.T) {
fmt.Println("")
Initialize("127.0.0.1:5001", "192.168.189.141")
fmt.Println(AddFile("/root/mount.sh"))
}
|
package binance
import (
"context"
"net/http"
)
// CreateMarginOrderService create order
type CreateMarginOrderService struct {
c *Client
symbol string
side SideType
orderType OrderType
quantity *string
quoteOrderQty *string
price *string
sto... |
package migrations
import "gorm.io/gorm"
type IMigrations interface {
Up() error
Down() error
}
func _addColumnsToTable(db *gorm.DB, dst interface{}, column string) error {
if !db.Migrator().HasColumn(dst, column) {
if err := db.Migrator().AddColumn(dst, column); err != nil {
return err
}
}
return nil
} |
package database
import (
"context"
"database/sql"
"strings"
"sync"
"time"
logger "github.com/panlibin/vglog"
"github.com/panlibin/virgo"
// mysql driver
_ "github.com/go-sql-driver/mysql"
)
const defaultQueryChannelSize = 1024
const (
queryTypeQuery int32 = iota
queryTypeQueryRow
queryTypeExec
)
type ... |
package main
import (
"os"
"github.com/jinmukeji/jiujiantang-services/api-jinmuid/config"
"github.com/jinmukeji/jiujiantang-services/api-jinmuid/rest"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/web"
)
var (
apiBase string
jwtSignInKey string
debug bool
)
func main() {
service := we... |
func minCostToMoveChips(position []int) int {
odd := 0
even := 0
for _, value := range position {
if value % 2 == 0 {
even++
} else {
odd++
}
}
if even < odd {
return even
} else {
return odd
}
} |
package main
import (
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type INFORMATRIONALL struct {
ID int `gorm:"column:id"`
Url string `gorm:"column:url"`
Title string `gorm:"column:title"`
Author string `gorm:"column:author"`
S... |
package puzzle
import (
"fmt"
"math/rand"
"sync"
"time"
)
func initPopulation(n int, size int, cm []int) ([][]int, []int) {
population := make([][]int, size)
fitness := make([]int, size)
for i := range population {
p := RandomPuzzle(n, cm)
population[i] = p
fitness[i], _ = Evaluate(n, p)
}
return popul... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/6/30 9:12 上午
# @File : jz_11_二进制中1的个数.go
# @Description :
# @Attention :
*/
package offer
func NumberOf1(n int) int {
count := 0
for n > 0 {
count++
n = n & (n - 1)
}
return count
}
|
package toolkit
import (
"testing"
)
func TestGenerateSectionIntSliceOfOrderly(t *testing.T) {
t.Logf("Generate orderly slice:%+v\n", GenerateSectionIntSliceOfOrderly(1, 20, 3))
}
func TestGenerateSectionIntSliceOfDisorderly(t *testing.T) {
t.Logf("Generate disorderly slice:%+v\n", GenerateSectionIntSliceOfDisord... |
package middleware
import (
"fmt"
"net/http"
"os"
"time"
"github.com/agungdwiprasetyo/reverse-proxy/helper"
)
type responseWriter struct {
http.ResponseWriter
statusCode int
}
// WriteHeader implement http.ResponseWriter
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWrit... |
package eth
import (
"bytes"
"math/big"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"go.... |
/*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the 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 ... |
package main
import (
"errors"
"fmt"
"os"
"github.com/spf13/cobra"
"path/filepath"
)
const desc = `
Merge one or more YAML files of values.
$ helm values mychart -f path/to/merging/file
To write to a file, instead of stdout, use '-o':
$ helm values mychart -f path/to/merging/file -o path/to/output/dir/
`
fun... |
package main
import (
"fmt"
"time"
)
func main() {
i := 0
for i < 5 { // não há while em go
fmt.Println(i)
i++
}
for j := 0; j <= 20; j += 2 {
fmt.Println(j)
}
for { //laço infinito
fmt.Println("Loop infinito")
time.Sleep(time.Second)
}
}
|
package node
import (
"context"
"crypto/tls"
"fmt"
"time"
"github.com/drand/drand/cmd/relay-gossip/lp2p"
"github.com/drand/drand/log"
"github.com/drand/drand/protobuf/drand"
"github.com/gogo/protobuf/proto"
bds "github.com/ipfs/go-ds-badger2"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-... |
package gotest
import (
"github.com/mumoshu/gosh"
"github.com/mumoshu/gosh/context"
)
func New() *gosh.Shell {
sh := &gosh.Shell{}
sh.Export("hello", func(ctx context.Context, target string) {
context.Stdout(ctx).Write([]byte("hello " + target + "\n"))
})
return sh
}
func MustExec(osArgs []string) {
New()... |
package ffuf
const (
//VERSION holds the current version number
VERSION = "0.12git"
)
|
package main
import (
"fmt"
"testing"
c "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
)
func TestCidConv(t *testing.T) {
cidv0 := "QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"
cidv1 := "zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi"
cid, err := c.Decode(cidv0)
if err != nil {
t.Fata... |
package app
func (a *App) GetNewestRecord() *Record {
a.Lock()
defer a.Unlock()
if len(a.records) == 0 {
return nil
}
rec := a.records[0]
for i := 1; i < len(a.records); i++ {
if rec.Start.Before(a.records[i].Start) {
rec = a.records[i]
}
}
return &rec
}
func (a *App) AddRecord(rec Record) error {
... |
package modules
import (
"bytes"
"encoding/json"
"fmt"
"github.com/logrusorgru/aurora"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
)
const (
BackendURL = "http://127.0.0.1:8080"
QueryURL = BackendURL + "/query"
LoginURL = BackendURL + "/login"
)
type Backend struct {
Name string
token string
}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.