code stringlengths 67 15.9k | labels listlengths 1 4 |
|---|---|
package taglog
// A map type specific to tags. The value type must be either string or []string.
// Users should avoid modifying the map directly and instead use the provided
// functions.
type Tags map[string]interface{}
// Add one or more values to a key.
func (t Tags) Add(key string, value ...string) {
for _, v :... | [
5
] |
/******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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/li... | [
3
] |
package router
import (
"github.com/lovego/goa"
)
type fieldCommentPair struct {
Field string
Comment string
}
type ResBodyTpl struct {
Code string `json:"code" c:"ok 表示成功,其他表示错误代码"`
Message string `json:"message" c:"与code对应的描述信息"`
Data interface{} `json:"data"`
}
const (
TypeReqBody uint8 ... | [
3
] |
package main
import (
"net/http"
"log"
"io/ioutil"
"encoding/json"
"github.com/gorilla/mux"
"time"
"fmt"
)
const URL = "https://api.opendota.com/api/proplayers"
var allPlayers []Player
var playerMap map[string]Player
func init() {
playerMap = make(map[string]Player)
}
func main() {
channel := make(chan []... | [
3
] |
//example with pointer receiver
package main
import (
"fmt"
)
type Person struct {
name string
age int
}
func (p *Person) fn(name1 string) {
p.name = name1
}
func main(){
p1:=&Person{name:"jacob",age:23}
p1.fn("ryan")
fmt.Println(p1.name);
} | [
3
] |
package netmodule
import (
"net"
"sync"
"sync/atomic"
)
//tcpsocket 对net.Conn 的包装
type tcpsocket struct {
conn net.Conn //TCP底层连接
buffers [2]*buffer //双发送缓存
sendIndex uint //发送缓存索引
notify chan int //通知通道
isclose uint32 //指示socket是否关闭
m sync.Mutex //锁
bclose bool ... | [
3
] |
package parser
import (
"github.com/almostmoore/kadastr/feature"
"github.com/almostmoore/kadastr/rapi"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"strconv"
"sync"
"time"
)
type FeatureParser struct {
session *mgo.Session
fRepo feature.FeatureRepository
rClient *rapi.Client
}
func NewFeatureParser(se... | [
6
] |
package rsa
import (
"CryptCode/utils"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"
"os"
)
const RSA_PRIVATE = "RSA PRIVATE KEY"
const RSA_PUBLIC = "RSA PUBLIC KEY"
/**
* 私钥:
* 公钥:
* 汉森堡
*/
func CreatePairKeys() (*rsa.PrivateKey,error) {
//1、先生成私钥
//var bi... | [
3,
6
] |
package Routes
import (
"freshers-bootcamp/week1/day4/Controllers"
"github.com/gin-gonic/gin"
)
//SetupRouter ... Configure routes
func SetupRouter() *gin.Engine {
r := gin.Default()
grp1 := r.Group("/user-api")
{
grp1.GET("products", Controllers.GetUsers)
grp1.POST("product", Controllers.CreateProd)
grp1.GE... | [
3
] |
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
type testCase struct {
rows int
cols int
grid [][]int
}
type testCaseOrErr struct {
testCase
err error
}
func main() {
reader := bufio.NewReader(os.Stdin)
testCases := loadTestCasesToChannel(reader)
var testIx int
for test := ... | [
6
] |
package utils
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"log"
"math"
"math/big"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/parnurzeal/gorequest"
"golang.org/x/xerrors"
pb "gopkg.in/cheggaaa/pb.v1"
)
var vulnListDir = filepath.Join(CacheDir(), "vuln-list")
func CacheDir() s... | [
1,
6
] |
package utils
const (
FloatType = CounterType("float64")
UintType = CounterType("uint64")
)
type CounterType string
type Counter interface {
Add(interface{})
Clone() Counter
Value() interface{}
}
type IntCounter uint64
func (ic *IntCounter) Add(num interface{}) {
switch n := num.(type) {
case uint64:
*i... | [
0
] |
package client
import (
"encoding/binary"
"encoding/json"
"errors"
protocol "github.com/sniperHW/flyfish/proto"
"reflect"
"unsafe"
)
const CompressSize = 16 * 1024 //对超过这个大小的blob字段执行压缩
type Field protocol.Field
func (this *Field) IsNil() bool {
return (*protocol.Field)(this).IsNil()
}
func (this *Field) Get... | [
3,
7
] |
package werckerclient
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/jtacoma/uritemplates"
)
// NewClient creates a new Client. It merges the default Config together with
// config.
func NewClient(config *Config) *Client {
c := &Client{config: defaultConfi... | [
6
] |
package gospelmaria
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/VividCortex/ewma"
"github.com/jmalloc/gospel/src/gospel"
"github.com/jmalloc/gospel/src/internal/metrics"
"github.com/jmalloc/gospel/src/internal/options"
"github.com/jmalloc/twelf/src/twelf"
"golang.org/x/ti... | [
5
] |
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/revand/App_Go_Larave_Angular_TEST/backend/go/awards"
"github.com/revand/App_Go_Larave_Angular_TEST/backend/go/users"
"github.com/revand/App_Go_Larave_Angular_TEST/backend/go/common"
"github.com/revand/App_Go_Larave_Angu... | [
3
] |
package main
import (
"fmt"
)
func fibc(N int) (int, int) {
a0, a1 := 1, 0
b0, b1 := 0, 1
if N == 0 {
return a0, a1
} else if N == 1 {
return b0, b1
}
var c0, c1 int
for i := 2; i <= N; i++ {
c0, c1 = a0+b0, a1+b1
a0, a1 = b0, b1
b0, b1 = c0, c1
}
return c0, c1
}
func main() {
var T, N int
f... | [
2
] |
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
//"github.com/aws/aws-sdk-go/service/ec2"
"flag"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/service/cloudwatch"
. "github.com/tnantoka/chatsworth"
"io/ioutil"
"log"
"strings"
"time"
)
func main() {
var p = flag.String(... | [
3
] |
package content
//CmdEventSetupUse is a command to setup event stream
const CmdEventSetupUse = "setup"
//CmdEventSetupShort is the short version description for vss event setup command
const CmdEventSetupShort = "Setup event stream"
//CmdEventSetupLong is the long version description for vss event setup command
cons... | [
3
] |
package metric_parser
import (
//"github.com/Cepave/open-falcon-backend/common/utils"
//"log"
)
type metricType byte
const (
MetricMax metricType = 1
MetricMin metricType = 2
MetricAvg metricType = 3
MetricMed metricType = 4
MetricMdev metricType = 5
MetricLoss metricType = 6
MetricCount metricType = 7
Met... | [
3
] |
package proxies
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
"github.com/vivasaayi/cloudrover/utililties"
)
type DataDogProxy struct {
ctx context.Context
apiClient *datadog.APIClient
apiKey string
appKey ... | [
6
] |
package server
import (
"net/http"
"log"
"fmt"
)
var mymux *http.ServeMux
const (
mailAddress string = "http://121.40.190.238:1280"
)
func Run() {
mymux = http.NewServeMux()
//绑定路由
bind()
err := http.ListenAndServe(":1280", mymux) //设置监听的端口
if err != nil {
log.Fatal("ListenAnd... | [
3
] |
package main
import (
"context"
"fmt"
"net"
"time"
"github.com/envoyproxy/go-control-plane/pkg/cache/types"
"github.com/envoyproxy/go-control-plane/pkg/cache/v2"
"github.com/golang/glog"
"github.com/golang/protobuf/ptypes"
"google.golang.org/grpc"
api "github.com/envoyproxy/go-control-plane/envoy/api/v2"
... | [
3
] |
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/juju/loggo"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/bson/primitive"
"github.com/mongodb/mongo-go-driver/mongo"
"github.com/mongodb/mongo-go-driver/mongo/options"
"githu... | [
6
] |
package deviceactionapi
import (
log "github.com/cihub/seelog"
)
// ActionRobotCleanerReq 发送MQTT命令的BODY
type ActionRobotCleanerReq struct {
CleanSpeed CleanSpeedOption `json:"clean_speed,omitempty"`
FindMe FindMeOption `json:"find_me,omitempty"`
StopClean StopCleanOption `json:"stop_cl... | [
3
] |
package service
import (
"net/http"
"bytes"
"time"
"errors"
"io/ioutil"
"encoding/json"
"X/goappsrv/src/helper"
"X/goappsrv/src/model"
)
type airTableRecord struct {
Id string `json:"id"`
Fields guestField `json:"fields"`
}
type AirTableList struct {
Records []airTableRecord ... | [
3
] |
package explicit
import (
"bitbucket.org/gofd/gofd/core"
"testing"
)
func alldifferentPrimitives_test(t *testing.T, xinit []int, yinit []int,
zinit []int, qinit []int, expx []int, expy []int,
expz []int, expq []int, expready bool) {
X := core.CreateIntVarExValues("X", store, xinit)
Y := core.CreateIntVarExValue... | [
6
] |
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
)
// GetIndex show Hello world !!
func GetIndex(c *gin.Context) {
c.String(http.StatusOK, "Hello world !!")
}
// GetFullName get request sample
func GetFullName(c *gin.Context) {
fname := c.DefaultQuery("firstname", "Guest")
lname := c.DefaultQue... | [
3
] |
// Copyright (c) 2014, Markover Inc.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
// Source code and contact info at http://github.com/poptip/ftc
package ftc
import (
"encoding/json"
"expvar"
"fmt"
"io"
"net/http"
"strings"
"time"
"code.google.com/p/go.ne... | [
5
] |
package structs
type UserLoginParams struct {
UserName string `valid:"Required;MaxSize(20)" form:"user_name"`
Password string `valid:"Required;MinSize(6);MaxSize(16)" form:"password"`
} //用户登录参数 | [
3
] |
package main
import (
"fmt"
"io/ioutil"
"math"
"os"
"strings"
)
const TOTALROWS = 128
const TOTALCOLUMNS = 8
func main() {
f, _ := os.Open("day5_input.txt")
b, _ := ioutil.ReadAll(f)
input_string := string(b)
lines := strings.Split(input_string, "\n")
lines = lines[0 : len(lines)-1]
var seats [][]int = m... | [
0,
1
] |
package time_series
import (
"fmt"
common "github.com/lukaszozimek/alpha-vantage-api-client"
)
const (
ONE_MINUTE = "1min"
FIVE_MINUTE = "5min"
FIFITHTEEN_MINUTE = "15min"
THIRTY_MINUTE = "30min"
SIXTY_MINUTE = "60min"
)
func TimeSeriesIntraDayInterval1minute(symbol string, apiKey string... | [
6
] |
package iplookup
import (
"strings"
"github.com/garyburd/redigo/redis"
"../db"
"fmt"
)
type IpInfo struct {
ID string //id编号
IP string //ip段
StartIP string //开始IP
EndIP string //结束IP
Country string //国家
Province string //省
City string //市
District string //区
Isp string //运营商
Typ... | [
3
] |
package main
import (
"fmt"
"math/rand"
"os"
//"text/tabwriter"
"strconv"
"time"
"sort"
)
/*
func myQuicksort (list []int) []int {
if len(list) <= 1 {
return list
}
}
func findPivot(list []int) int {
listLen = len(list)
if listLen < 3 {
return list[0]
}
first := list[0]
middle := list[listLen/2]
... | [
3
] |
// Package logrus_pgx provides ability to use Logrus with PGX
package logrus_pgx
import (
"github.com/sirupsen/logrus"
)
// pgxLogger type, used to extend standard logrus logger.
type PgxLogger logrus.Logger
// pgxEntry type, used to extend standard logrus entry.
type PgxEntry logrus.Entry
//Print and format debug ... | [
3
] |
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
)
func CreateMessage(message model.Message) (err error) {
//global.GVA_DB.AutoMigrate(&message)
err = global.GVA_DB.Create(&message).Error
return err
} | [
3
] |
package url_test
import (
"fmt"
"testing"
"github.com/barolab/candidate/url"
)
type WithoutQueryTestCase struct {
argument string
expected string
err error
}
func TestWithoutQuery(T *testing.T) {
cases := []WithoutQueryTestCase{
{argument: "", expected: "", err: fmt.Errorf("Cannot exclude URL query fr... | [
2
] |
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
//允许追加空切片
numbers = append(numbers,0)
printSlice(numbers)
//向空切片添加一个元素
numbers = append(numbers,1)
printSlice(numbers)
//同时添加多个元素
numbers = append(numbers,2,3,4)
printSlice(numbers)
//创建切片 number1 是之前 切片容量的两倍,容量的值只有1,2,... | [
3
] |
package gragh
func dijkstraMatrix(g *matrix, src int) (dist []int, sptSet []int) {
sptSet = make([]int, g.n)
dist = make([]int, g.n)
pred := make([]int, g.n)
for i := range dist {
dist[i] = INF
sptSet[i] = -1
pred[i] = -1
}
dist[src] = 0
pred[src] = src
for i := 0; i < g.n; i++ {
mindist := INF
minve... | [
5,
6
] |
package install
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
)
func PathExists(path, fileName string) bool {
filePath := path + fileName
_, err := os.Stat(filePath)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
func Download(FileName string, FilePath string) {
... | [
2,
6
] |
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
*/
package guid
import (
"fmt"
"syscall"
"golang.org/x/sys/windows"
)
//sys clsidFromString(lpsz *uint16, pclsid *windows.GUID) (hr int32) = ole32.CLSIDFromString
//
// FromString parses "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXX... | [
3
] |
package stats
import (
"github.com/fm2901/bank/v2/pkg/types"
)
func Avg(payments []types.Payment) types.Money {
var allSum types.Money
var allCount types.Money
if len(payments) < 1 {
return 0
}
for _, payment := range payments {
if payment.Status == types.StatusFail {
continue
}
allSum += payment.A... | [
0,
6
] |
//Priority Queue in Golang
/*
In the Push and Pop method we are using interface
Learn these :
interface{} is the empty interface type
[]interface{} is a slice of type empty interface
interface{}{} is an empty interface type composite literal
[]interface{}{} is a slice of type empty interface composite literals
Wha... | [
3
] |
package mocks
import (
"app/models"
"reflect"
"testing"
"time"
)
func TestUserMock(t *testing.T) {
ID := 0
users := &UserMock{}
user := &models.User{
ID: ID,
Name: "test user",
Email: "test@test.com",
Icon: "testicon",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
users.Cre... | [
6
] |
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
numPrisoners := 1000
numHats := 1001
// there are 1000 prisoners
prisoners := make([]int, numPrisoners)
// and 1001 hats
hats := make([]int, numHats)
for i := 0; i < numHats; i++ {
hats[i] = i + 1
}... | [
5
] |
package db
import (
"database/sql"
"fmt"
"time"
"gopkg.in/vmihailenco/msgpack.v2"
)
func (db DB) EnsureQueuesExist(queueNames []string) error {
for _, queueName := range queueNames {
if err := db.FirstOrCreate(&Queue{}, Queue{Name: queueName}).Error; err != nil {
return fmt.Errorf("couldn't create queue %s... | [
6
] |
package main
import (
"fmt"
)
func main() {
//Program to print number in decimal, binary, hex
x := 10
fmt.Printf("%d,%b,%#x", x, x, x)
}
| [
3
] |
package pd
import (
"strings"
"time"
"github.com/juju/errors"
"github.com/zssky/log"
"github.com/taorenhai/ancestor/client"
"github.com/taorenhai/ancestor/meta"
)
const (
maxRetryInterval = time.Minute
minReplica = 3
)
type delayRecord struct {
timeout time.Time
interval time.Duration
}
func newD... | [
0,
6
] |
package Redis
import (
"github.com/go-redis/redis/v8"
"context"
"log"
)
var ctx = context.Background()
type Redis struct{
//Main structure for redis client.
//It has connection field to save
//redis-client connection.
connection *redis.Client
}
func (r *Redis)Connect(){
//Connects to redis server.
conn... | [
2,
3
] |
package guess_number_higher_or_lower
// https://leetcode.com/problems/guess-number-higher-or-lower
// level: 1
// time: O(log(n)) 0ms 100%
// space: O(1) 1.9M 100%
var pick int
func guess(num int) int {
if num == pick {
return 0
} else if num > pick {
return -1
} else {
return 1
}
}
// leetcode submit re... | [
5
] |
package main
import "fmt"
// Celsius ...
type Celsius float64
// ToF convert Celsius to Fahrenheit
func (c Celsius) ToF() Fahrenheit {
return CToF(c)
}
// Fahrenheit ...
type Fahrenheit float64
// ToC convert Celsius to Fahrenheit
func (f Fahrenheit) ToC() Celsius {
return FToC(f)
}
// const variable
const (
A... | [
3
] |
package main
import (
"fmt"
"github.com/veandco/go-sdl2/sdl"
)
type field struct {
squares squares
selected int
}
type square struct {
R sdl.Rect
}
// ID of the square
type ID int32
type squares []square
func createSquares(startX, startY, width, height, spacing int32) (sq squares) {
var x, y int32
for i... | [
5
] |
// Take a number: 56789. Rotate left, you get 67895.
//
// Keep the first digit in place and rotate left the other digits: 68957.
//
// Keep the first two digits in place and rotate the other ones: 68579.
//
// Keep the first three digits and rotate left the rest: 68597. Now it is over since keeping the first four it r... | [
5
] |
package http_proxy_middleware
import (
"fmt"
"github.com/didi/gatekeeper/model"
"github.com/didi/gatekeeper/public"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
//匹配接入方式 基于请求信息
func HTTPWhiteListMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
serviceDetail, err := model.GetServiceDetailFr... | [
3
] |
package streamtcp
import (
"bufio"
// "errors"
"fmt"
"log"
"net"
"time"
)
type CallBackClient func(*Session, string)
type Session struct {
conn net.Conn
incoming Message
outgoing Message
reader *bufio.Reader
writer *bufio.Writer
quiting chan net.Conn
name string
closing b... | [
3
] |
package db_node
import (
"github.com/solympe/Golang_Training/pkg/pattern-proxy/db-functions"
)
type dbNode struct {
cache db_functions.DBFunctions
dataBase db_functions.DBFunctions
}
// SendData updates data in the main data-base and cache
func (n *dbNode) SendData(data string) {
db_functions.DBFunctions.Send... | [
6
] |
package companyreg
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//di... | [
3
] |
package main
import yaml "gopkg.in/yaml.v2"
// Convertable parses input as array of bytes into "from" version, then calls
// convert function which needs to be implemented in specific version conversion
// then it marshals yaml into "out" version and returns the array of bytes of
// that yml file
// Args:
// in inter... | [
6
] |
package main
type MyStack struct {
val []int
}
/** Initialize your data structure here. */
func Constructor() MyStack {
return MyStack{[]int{}}
}
/** Push element x onto stack. */
func (this *MyStack) Push(x int) {
this.val = append([]int{x},this.val...)
}
/** Removes the element on top of the stack and retu... | [
3
] |
package lessons
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m, n := len(obstacleGrid), len(obstacleGrid[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if obstacleGrid[i][j] == 1 {
f[i][j] = 0
} else if i == 0 && j... | [
5
] |
package cookie
import (
"errors"
"net/http"
"time"
"github.com/gorilla/securecookie"
)
type AuthCookie struct {
Data string `json:"data"`
OrgCID string `json:"org_custom_id"`
SubscriptionID int32 `json:"subscription_id"` // used to check if internal/admin (sub 9999)
}
type SecureCookie str... | [
6
] |
package config
import (
"bytes"
"errors"
"fmt"
"html/template"
"github.com/spf13/viper"
)
//ErrKey raise when an key is unknown.
var ErrKey = errors.New("KeyError")
// Default values.
var defaults = map[string]interface{}{
"out_file": "/tmp/jocasta_{{.App}}_stdout.log",
"out_maxsize": "0",
"out_backups":... | [
3,
6
] |
package main
/******************** Testing Objective consensu:STATE TRANSFER ********
* Setup: 4 node local docker peer network with security
* 0. Deploy chaincodeexample02 with 100000, 90000 as initial args
* 1. Send Invoke Requests on multiple peers using go routines.
* 2. Verify query results match on PEER0... | [
0,
3
] |
package toml
import (
"time"
"strconv"
"runtime"
"strings"
"fmt"
)
type Tree struct {
Root *ListNode // top-level root of the tree.
text string
lex *lexer
token [3]token // three-token lookahead for parser.
peekCount int
}
func Parse(text string) (tree *Tree, err error) {
defer parse... | [
3
] |
package cmd
import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
"github.com/snowdrop/k8s-supervisor/pkg/common/config"
"github.com/snowdrop/k8s-supervisor/pkg/common/oc"
)
var (
ports string
)
var debugCmd = &cobra.Command{
Use: "debug [flags]",
Short: "Debug... | [
3
] |
package articles
import (
"github.com/PuerkitoBio/goquery"
"github.com/yevchuk-kostiantyn/WebsiteAggregator/models"
"log"
"strings"
)
func Search(config *models.Article) {
response, err := goquery.NewDocument(config.URL)
log.Println("New Search", config)
if err != nil {
panic("Bad URL!")
}
article := ""
... | [
6
] |
package detector
import (
"fmt"
"reflect"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/token"
"github.com/wata727/tflint/config"
"github.com/wata727/tflint/evaluator"
"github.com/wata727/tflint/issue"
"github.com/wata727/tflint/logger"
)
type Detector struct {
ListMap map[s... | [
5
] |
package chat
//User reprenent of User model
type User struct {
Name string `json:"name"`
Username string `json:"username"`
}
//ResponseJoin represent of joined message
type ResponseJoin struct {
Success bool `json:"success"`
Message string `json:"message"`
Username string `json:"username"`
}
//Message r... | [
3
] |
package blockchain
import (
"crypto/sha1"
"fmt"
)
//Block construct
type Block struct {
id int
hash string
previousBlockHash string
Content []byte
}
//BlockChain type
type BlockChain struct {
currentID int
blocks []*Block
}
func hash(ip []byte) string {
sha1 := sha1... | [
0,
3
] |
package dynamo
import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
apperror "github.com/jayvib/app/apperr"
"github.com/jayvib/app/model"
"github.... | [
3
] |
package main
import "encoding/json"
import "fmt"
import "os"
// 下面我们将使用这两个结构体来演示自定义类型的编码和解码。
type Response1 struct {
Page int
Fruits []string
}
type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
func main() {
b := []byte(`{
"Title": "Go语言编程",
"Authors": ["XuShiw... | [
3
] |
package web
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/mail"
"net/smtp"
)
// SSL/TLS Email Example, doesn't work ....
func SendEmail() {
from := mail.Address{"John Lau", "soulmanjohn@163.com"}
to := mail.Address{"John Lau", "soulmanjohn@163.com"}
subj := "This is the email subject"
body := "This is an exa... | [
3,
6
] |
package main
import "fmt"
func main() {
x := 0 //narrow scope instead of using a global scope variable
increment := func() int{ // This line is a nested function in go as well as an anonymous function
x++ // an anon function is a function without a name, it looks like a function that is
return x // a... | [
3
] |
package pipedrive
import (
"context"
"fmt"
"net/http"
)
// DealService handles deals related
// methods of the Pipedrive API.
//
// Pipedrive API dcos: https://developers.pipedrive.com/docs/api/v1/#!/Deals
type DealService service
// Deal represents a Pipedrive deal.
type Deal struct {
ID int `json:"i... | [
6
] |
/*
Copyright 2018 The Knative 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... | [
3
] |
package styx
import (
"encoding/binary"
)
// i, j, k, l... are int indices
// p, q, r... are string variable labels
// u, v, w... are *Variable pointers
// x, y... are dependency slice indices, where e.g. iter.In[p][x] == i
func (iter *Iterator) next(i int) (tail int, err error) {
var ok bool
tail = iter.Len()
/... | [
1
] |
package cal_test
import (
"fmt"
"testing"
)
// 链表的一个节点
type ListNode struct {
prev *ListNode // 前一个节点
next *ListNode // 后一个节点
value interface{} // 数据
}
// 创建一个节点
func NewListNode(value interface{}) (listNode *ListNode) {
listNode = &ListNode{
value: value,
}
return
}
// 当前节点的前一个节点
func (n *ListNode... | [
0,
1,
3
] |
package k8scomponents_test
import (
"errors"
"testing"
"github.com/kyma-incubator/github-slack-connectors/scenario/github-issue-sentiment-analysis/internal/k8scomponents"
"github.com/stretchr/testify/assert"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/kyma-incubator... | [
3
] |
// This code is either inspired from or taken directly from go's tls package
package noise
import (
"errors"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Conn represents a secured connection.
// It implements the net.Conn interface.
type Conn struct {
conn net.Conn
isClient bool
// handshake
con... | [
6
] |
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
... | [
6
] |
package main
import (
"bytes"
"flag"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"io/ioutil"
"math"
"net/http"
"os"
"os/exec"
"sort"
"strings"
)
func GetRange(c uint8) int {
if 0 <= c && c < 85 {
return 0
} else if 85 <= c && c < 170 {
return 1
} else if 170 <= c && c <= 255 {
return 2
}
... | [
0,
2,
5
] |
package libsignal
import (
"bytes"
"crypto/sha1"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"golang.org/x/crypto/pbkdf2"
log "github.com/Sirupsen/logrus"
"math/rand"
"github.com/OpenBazaar/libsignal/ratchet"
)
// store implements the PreKeyStore, SignedPreKeyStore,
// Id... | [
3
] |
package headers
import (
"log"
"net/http"
"path"
"strings"
)
var contentTypes map[string]string
var defaultHeaders map[string]string
func init() {
// Set content types
contentTypes = make(map[string]string)
contentTypes[".html"] = "text/html"
contentTypes[".css"] = "text/css"
contentTypes[".svg"] = "image/s... | [
6
] |
package random
import (
"math/rand"
)
//
//Random generator for float values.
//
//Examples:
//
// value1 := RandomFloat.nextFloat(5, 10); // Possible result: 7.3
// value2 := RandomFloat.nextFloat(10); // Possible result: 3.7
// value3 := RandomFloat.updateFloat(10, 3); // Possible result: 9.2
type ... | [
1,
3,
6
] |
package service
import (
"github.com/aidar-darmenov/message-delivery-client/config"
"github.com/aidar-darmenov/message-delivery-client/interfaces"
"github.com/aidar-darmenov/message-delivery-client/model"
"go.uber.org/zap"
"log"
"net"
"strconv"
)
type Service struct {
Configuration interfaces.Configuration
... | [
3
] |
package books
import (
"encoding/json"
"errors"
"fmt"
"github.com/ikalkali/es-golang/elasticsearch"
"github.com/ikalkali/es-golang/entity/queries"
)
const (
indexItems = "books"
typeItem = "_doc"
)
func (b *Books) Save() error {
result, err := elasticsearch.Client.Index(indexItems, typeItem, b)
if err !=... | [
6
] |
package tag
import (
"github.com/goEventListingAPI/entity"
)
//add event tags
//AddEventTag(id []int)(*entity.Tag, []error) //?? how do we add multiple tags
//notify(eventID uint, tagsID []int) []error //this should be done separatly in notification section
//get the event tags
//GetTags() ([]entity.Tag, []error... | [
3
] |
package go_dev
import (
"database/sql"
"fmt"
"github.com/lib/pq"
)
/*
Initializes a new task for a project and adds it to the database
If succesful, returns true
Otherwise, returns false
*/
func CreateTask(project_name, project_owner, task_name string, db *sql.DB) bool {
sqlStatement1 := `SELECT id FROM project... | [
3,
5,
6
] |
package search
import "testing"
func compare(X, Y []string) bool {
for i := 0; i < len(X); i++ {
if X[i] != Y[i] {
return false
}
}
return true
}
func TestSuffixTree(t *testing.T) {
words := []string{
"aardvark",
"happy",
"hello",
"hero",
"he",
"hotel",
}
answers := SuffixTree(words, "he")
... | [
2
] |
package servo
import (
"fmt"
"strings"
"sync"
"time"
)
type flag uint8
// is check if the given bits are set in the flag.
func (f flag) is(bits flag) bool {
return f&bits != 0
}
// String implements the Stringer interface.
func (f flag) String() string {
if f == 0 {
return "( NONE )"
}
s := new(strings.B... | [
1,
2
] |
package schema
import (
"context"
"fmt"
"reflect"
"strings"
"hermes/models"
"github.com/fatih/structs"
"github.com/iancoleman/strcase"
"github.com/jinzhu/gorm"
graphqlErrors "github.com/neelance/graphql-go/errors"
)
type (
entity struct {
Table string
Field *string
}
field struct {
Name string
... | [
0,
5
] |
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | [
6
] |
package main
//给定一个整数 n,返回 n! 结果尾数中零的数量。
//
// 示例 1:
//
// 输入: 3
//输出: 0
//解释: 3! = 6, 尾数中没有零。
//
// 示例 2:
//
// 输入: 5
//输出: 1
//解释: 5! = 120, 尾数中有 1 个零.
//
// 说明: 你算法的时间复杂度应为 O(log n) 。
// Related Topics 数学
// 👍 389 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
func trailingZeroes(n int) i... | [
3
] |
package main
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
"log"
"time"
)
func main() {
var (
conf clientv3.Config
client *clientv3.Client
err error
kv clientv3.KV
delRes *clientv3.DeleteResponse
)
conf = clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: 5 * ... | [
3
] |
package array
import "container/list"
//输入:nums = [10,2,-10,5,20], k = 2
//输出:37
//解释:子序列为 [10, 2, 5, 20]
func ConstrainedSubsetSum(nums []int, k int) int{
var l int = len(nums)
var q list.List //q.PushBack(nums[0])//store idx from "i - k" to "i - 1",decrease sort
var dp []int = make([]int,l)//dp[i]:the biggest su... | [
3
] |
package flexible_reflect
import (
"errors"
"reflect"
"testing"
)
type Employee struct {
EmployeeID string
Name string //`format:"normal"` //struct tag
Age int
}
type Customer struct {
CookieID string
Name string
Age int
}
func fillBySettings(st interface{}, settings map[string]interfa... | [
3
] |
package file
import (
"bufio"
"fmt"
"github.com/haplone/tidb_test/utils"
"io"
"io/ioutil"
"log"
"os"
"strings"
)
func GetDbCfgs(FoldName, FileName string) []DbCfg {
var dbs []DbCfg
dbNames := ParseDbNames(FoldName, FileName)
for _, n := range dbNames {
db := NewDbCfg(FoldName, n)
dbs = append(dbs, db)... | [
0,
2,
3
] |
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
fmt.Println("Program started...")
var programOption int64
fmt.Println(
`Select a program option by entering a number:
1: Command line input to return SHA512 Base64 encoded hash
2: Hash and encode passwords over HTTP
... | [
5
] |
package assignment02IBC_master
type Transaction struct {
Amount int
Sender string
Receiver string
}
func (T Transaction) IsEmpty() bool{
if T.Amount == 0 && T.Receiver == "" && T.Sender == "" {
return true
}
return false
} | [
2
] |
package controllers
import (
"github.com/astaxie/beego"
"strings"
)
type SiteController struct {
BaseController
}
//Login page
func (this *SiteController) Login() {
this.Layout = "layout/login.html"
if this.IsLogin() {
this.Redirect(beego.URLFor("SiteController.Index"))
}
if this.IsPost() {
phone := str... | [
3
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.