text stringlengths 11 4.05M |
|---|
/*
* Copyright 2018- The Pixie 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... |
// 출처: https://github.com/gonet2/agent
package scommon
import (
"encoding/binary"
"errors"
"reflect"
)
// 타입의 크기를 계산한다
func Sizeof(t reflect.Type) int {
switch t.Kind() {
case reflect.Array:
//fmt.Println("reflect.Array")
if s := Sizeof(t.Elem()); s >= 0 {
return s * t.Len()
}
case reflect.Struct:
/... |
package post_order_traversal
import "testing"
func TestSolve(t *testing.T) {
root := &Node{val: 1}
root.left = &Node{val: 2}
root.right = &Node{val: 3}
root.left.left = &Node{val: 4}
root.left.right = &Node{val: 5}
root.right.left = &Node{val: 6}
root.right.right = &Node{val: 7}
postOrder(root)
}
|
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
configv1client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1"
"github.com/sirupsen/logrus"
k8sscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/clientcmd"
utilclock "k8s.io/utils/clock"
"github.com/... |
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// 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... |
// Package models contains the types for schema 'public'.
package models
// GENERATED BY XO. DO NOT EDIT.
import (
"database/sql/driver"
"errors"
)
// ActivityType is the 'activity_type' enum type from schema 'public'.
type ActivityType uint16
const (
// ActivityTypeApplicationCreated is the 'application_created... |
package prime
import ()
const testVersion = 2
// Compute the prime factors of a given natural number.
// Return prime factors in increasing order
// eg. Given 60, return 2, 2, 3, 5
// Very slow: BenchmarkPrimeFactors-4 100 11950683 ns/op
func Factors(number int64) []int64 {
ret := []int64{}
var i int64
... |
package main
import (
"net/http"
"time"
"github.com/lilwulin/lilraft"
)
func main() {
var array []int
config := lilraft.NewConfig(
lilraft.NewHTTPNode(1, "http://127.0.0.1:8787"),
lilraft.NewHTTPNode(2, "http://127.0.0.1:8788"),
lilraft.NewHTTPNode(3, "http://127.0.0.1:8789"),
)
s := lilraft.NewServer(1... |
package main
// https://nick.groenen.me/posts/2017/01/09/plugins-in-go-18/
import "C"
func Greet() string {
return "Hello World"
}
|
package database
import (
"strings"
"github.com/direktiv/direktiv/pkg/flow/database/recipient"
"github.com/direktiv/direktiv/pkg/refactor/core"
)
type HasAttributes interface {
GetAttributes() map[string]string
}
func GetAttributes(recipientType recipient.RecipientType, a ...HasAttributes) map[string]string {
... |
package assembler
import (
"math/rand"
"testing"
)
func ismaxtest(t *testing.T, b *testing.B) {
for j := 0; j < 100; j++ {
if b != nil {
b.StopTimer()
}
x := make([]float32, j)
for i := range x {
x[i] = float32(rand.NormFloat64())
}
if b != nil {
b.StartTimer()
for i := 0; i < b.N; i++ {
... |
// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package sources
import (
"fmt"
"github.com/OWASP/Amass/amass/core"
"github.com/OWASP/Amass/amass/utils"
)
// PTRArchive is data source object type that implements t... |
/*
Copyright 2019 Netfoundry, 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
package main
/*
All Methods which belong to the Database Communication.
*/
import (
"database/sql"
"golang.org/x/crypto/bcrypt"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
/*
Represents a User in the Database.
*/
type User struct {
UserID uint64
Username string
passwordHash string
... |
package movie
type RegularMovie struct {
Param
}
func (r RegularMovie) GetCost(days int) float64 {
if days <= 2 {
return 2.0
}
return 2 + (float64(days) - 2) * 1.5
}
func (r RegularMovie) GetPoint(days int) int {
return 1
}
func (r RegularMovie) GetTitle() string {
return r.Title
} |
package main
import(
"fmt"
)
func main() {
a := 10.000
b := 1.2
c := 1 + 2.12i
d := "this is so random!"
e := 'x'
a = a + b
a = a - b
a = a * b
a = a / b
m := make(map[int]int)
m[1] = 2
m[2] = 4
m[3] = m[2] % m[1]
m[3] += m[2]
m[3] -= m[2]
m[3] *= m[2]
m[3] /= m[2]
m[3] %= m[2]
m[3] << 1
var ... |
package run
import (
"errors"
"fmt"
"os/user"
"path/filepath"
"github.com/messagedb/messagedb/cluster"
"github.com/messagedb/messagedb/db"
"github.com/messagedb/messagedb/meta"
"github.com/messagedb/messagedb/services/admin"
"github.com/messagedb/messagedb/services/hh"
"github.com/messagedb/messagedb/servic... |
package main
import (
"bytes"
"fmt"
"net/http"
"net/http/httputil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"testing"
)
func TestBasicExample(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Basic Example Suite")
}
var _ = Describe("Basic Example", ... |
package main
import (
"fmt"
"math/rand"
"os"
"sync"
"time"
)
var source = rand.NewSource(time.Now().Unix())
var randN = rand.New(source)
var choices = [3]string{"rock", "paper", "scissors"}
func main() {
opponentChoice := make(chan string, 1)
var userChoice string
var wg sync.WaitGroup
wg.Add(1)
go randomC... |
/*
Copyright 2019 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, ... |
package main
import "fmt"
func forDemo() {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
// 2.8.1
func nineXnine() {
for i := 1; i <= 9; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("%d * %d = %-2d ", i, j, i*j)
}
fmt.Println()
}
}
// 4.8.1
func arraySum() {
var sum = 0
var arraySum = [...]int{1, 3, ... |
package main
import "fmt"
// 配列は固定長だが、スライスは可変長で柔軟。
//
func main() {
primes := [6]int{2, 3, 5, 7, 11, 12}
var s []int = primes[0:1]
fmt.Println(s)
}
|
package post
import "errors"
// Error codes for violation of post entity rules
var (
ErrBadPostContent = errors.New("Post: Content was not provided with the enough data")
ErrNoFoundPost = errors.New("Post: Post with id was not found")
ErrMissingPostPicture = errors.New("Post: Post picture is mandatory")... |
package cmd
import (
"os"
"github.com/spf13/cobra"
"github.com/Zenika/marcel/backoffice"
"github.com/Zenika/marcel/config"
)
func init() {
var cfg = config.New()
var cmd = &cobra.Command{
Use: "backoffice",
Short: "Starts Marcel's Backoffice server",
Args: cobra.NoArgs,
PreRunE: preRunForServer(c... |
package main
import "fmt"
func main(){
elements := map[string]map[string]string{
"H":map[string]string{
"name":"Hydrogen",
"state":"gas",
},
"He":map[string]string{
"name":"Helium",
"state":"gas",
},
}
if el,ok:=elements["He"];ok{
fmt.Println(el["name"],el["state"])
}
}
|
package services
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"docktor/server/storage"
"docktor/server/types"
"github.com/labstack/echo/v4"
)
// getAll find all
func getAll(c echo.Context) error {
db := c.Get("DB").(*storage.Docktor)
s, err := db.Services().FindAll()
if err != nil {
return c.JSON(http.... |
package freshdesk
import (
"testing"
"github.com/leebenson/conform"
)
func TestTicket(t *testing.T) {
t.Skip("Need account info to test this")
client, err := NewClient("", "")
if err != nil {
t.Fatalf("Could not create client: %s\n", err)
}
ticket := &Ticket{
Email: "testuser@example.com",
Name:... |
package p2pNetwork
import (
"encoding/json"
"errors"
"fmt"
"github.com/HNB-ECO/HNB-Blockchain/HNB/config"
"github.com/HNB-ECO/HNB-Blockchain/HNB/logging"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/common"
msgtypes "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/bean"
"github.com/HNB-ECO/HNB-Bl... |
package secrets
import (
"fmt"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cli/user"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/terminal"
"github.com/10gen/realm-cli/internal/utils/flags"
)
// CommandMetaList is the command meta for... |
package main
import "fmt"
// 结构体实现”继承“
type animal struct {
name string
}
// 给animal实现一个西东的方法
func (a animal) move() {
fmt.Printf("%s会动。", a.name)
}
// 狗类
type dog struct {
feet uint8
animal
}
// 给狗实现一个汪汪汪的方法
func (d dog) wang() {
fmt.Printf("%s会汪汪汪~", d.name)
}
func main() {
d1 := dog{
feet: 4,
animal:... |
package dcmdata
import (
"testing"
)
func TestNewDcmInputStream(t *testing.T) {
cases := []struct {
in *DcmProducer
want *DcmInputStream
}{
{new(DcmProducer), &DcmInputStream{}},
}
for _, c := range cases {
got := NewDcmInputStream(c.in)
if *got != *c.want {
t.Errorf("NewDcmInputStream(%v) == want... |
package sudoku
import (
"fmt"
"math/rand"
)
type xwingTechnique struct {
*basicSolveTechnique
}
func (self *xwingTechnique) humanLikelihood(step *SolveStep) float64 {
return self.difficultyHelper(50.0)
}
func (self *xwingTechnique) Description(step *SolveStep) string {
majorAxis := "NONE"
minorAxis := "NONE"
... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03800105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.038.001.05 Document"`
Message *SecuritiesSettlementTransactionModificationRequestV... |
package utils
import (
"bytes"
"fmt"
"io"
"strings"
"text/template"
"text/template/parse"
)
// PrefixRenderer writes data to pw
type PrefixRenderer = func(pw *PrefixWriter, params map[string]interface{})
// RenderTemplate renders templates respecting indentation
// Its intended use is for YAML templates
// che... |
package davepdf
import (
"fmt"
"strings"
)
type PdfPageTree struct {
id int
pages []*PdfPage
}
func (pdf *Pdf) newPageTree() *PdfPageTree {
pageTree := &PdfPageTree{}
pdf.newObjId()
pageTree.id = pdf.n
return pageTree
}
func (pdf *Pdf) AddPage() *PdfPage {
page := pdf.newPage()
pdf.page = page
ret... |
package elastiwatch
import (
"context"
"fmt"
"regexp"
"time"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1"
"github.com/malware-unicorn/managed-bots/base"
"github.com/olivere/elastic"
)
type LogWatch struct {
*base.DebugOutput
db *DB
cli *elastic.Client
index, email... |
package http
import (
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func RegisterRoutes(r chi.Router, meetUpHandler *MeetupHandler) {
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Heartbeat("/health"))
r.Use(securityMiddleware)
r.Route("/meetup", func(r chi.Router) {
r.... |
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
"github.com/frk/gosql/internal/testdata/common"
)
func (q *UpdateFilterResultSliceQuery) Exec(c gosql.Conn) error {
var queryString = `UPDATE "test_user" AS u SET (
"email"
, "full_name"
, "is... |
package services
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
"github.com/Juniper/contrail/pkg/common"
"github.com/Juniper/contrail/pkg/models"
)
type metadataGetter interface {
GetMetaData(ctx context.Context, uuid string, fqName []string)... |
// The hcledit tool provides a CRUD interface to attributes within a Terraform
// file.
package main
import (
"fmt"
"os"
"go.mercari.io/hcledit/cmd/hcledit/internal/command"
)
func main() {
cmd := command.NewCmdRoot()
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
|
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// Sms represents a row from 'sun.sms'.
// Manualy copy this to project
... |
package socketio
// import (
// "fmt"
// "net/http"
// engineio "github.com/googollee/go-engine.io"
// socketio "github.com/googollee/go-socket.io"
// )
// // Transport :
// type Transport struct {
// Port int
// Socket *socketio.Server
// }
// // SocketContext :
// type SocketContext struct {
// Query ma... |
package main
import (
"bufio"
"crypto/hmac"
"crypto/sha256"
"encoding/base32"
"encoding/json"
"fmt"
"github.com/nu7hatch/gouuid"
"io/ioutil"
"net/http"
"strings"
)
var userTokens = map[string]string{}
var userInfos = map[string]*userInfo{}
var secretKey []byte
var dataStore = &DataStore{}
var client_id st... |
package crawler
type Interface interface {
Scan(string, int) ([]Document, error)
}
type Document struct {
ID uint64
Title string
URL string
}
func (d Document) Ident() uint64 {
return d.ID
}
|
package repository
import (
"context"
"time"
"todo-go/config"
"todo-go/model"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type Noter interface {
ListNote() ([]model.Note, error)
AddNote(note model.Note) (interface{}, error)
DeleteNot... |
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Create("file1.txt")
if err != nil {
fmt.Println(err)
return
}
l, err := f.WriteString("Write Line one")
if err != nil {
fmt.Println(err)
f.Close()
return
}
fmt.Println(l, "bytes written")
err = f.Close()
if err != nil {
fmt.Println(e... |
package auth
import (
"errors"
"github.com/chfanghr/hydric/core/auth/models"
models2 "github.com/chfanghr/hydric/core/models"
"golang.org/x/crypto/bcrypt"
)
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
byteHash := []byte(hashedPwd)
return bcrypt.CompareHashAndPassword(byteHash, plainPwd) == n... |
/*
This package models any old event handler.
*/
package mockingsample
import (
"fmt"
"gsamples/mockingsample/dbaccess"
)
// The event handler struct. Models event attributes
type EventHandler struct {
name string // The name of the event
actor dbaccess.SomeFunctionalityGroup // The in... |
package sso
import (
"encoding/json"
"io/ioutil"
"net/http"
"golang.org/x/oauth2"
)
//GithubEnterpriseEndpoint generates an OAuth2 endpoint for a Github Enterprise installation.
func GithubEnterpriseEndpoint(domain string) oauth2.Endpoint {
return oauth2.Endpoint{
AuthURL: "https://" + domain + "/login/oauth... |
package bplustree
const (
MaxKV = 255
MaxKC = 511
)
type Node interface {
count() int
find(key []byte) (int, bool)
parent() *InteriorNode
setParent(*InteriorNode)
full() bool
isDirty() bool
setDirty(bool)
cache() (bool, []byte, []byte)
largestKey() []byte
encode() (value []byte)
decode(data []byte)
//D... |
package color
import "fmt"
type Code int
const None Code = -1
// Attributes.
const (
Reset Code = iota
Bold
Dim
Italic
Underline
Blink
BlinkFast
Inverse
Hidden
Strikethrough
)
// Foreground colors.
const (
Black Code = iota + 30
Red
Green
Yellow
Blue
Magenta
Cyan
LightGray
)
const (
DarkGray Co... |
package leetcode
import (
"reflect"
"testing"
)
func listEqual(h1, h2 *ListNode) bool {
p1, p2 := h1, h2
for ; p1 != nil && p2 != nil && p1.Val == p2.Val; p1, p2 = p1.Next, p2.Next {
}
if p1 != nil || p2 != nil {
return false
}
return true
}
func slice2List(slice []int) *ListNode {
var head, prev *ListNod... |
package sheets
import (
"context"
"fmt"
"golang.org/x/oauth2/google"
"google.golang.org/api/sheets/v4"
"io/ioutil"
)
type SheetClient struct {
srv *sheets.Service
spreadsheetID string
}
func NewSheetClient(ctx context.Context, spreadsheetID string) (*SheetClient, error) {
b, err := ioutil.ReadFile("se... |
package main
import (
"fmt"
"os"
"strings"
prompt "github.com/c-bata/go-prompt"
"github.com/c-bata/go-prompt/completer"
)
var filePathCompleter = completer.FilePathCompleter{
IgnoreCase: true,
Filter: func(fi os.FileInfo) bool {
return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
},
}
func executor(i... |
package prompt
import (
"fmt"
"os"
"strings"
)
func Confirm(msg string) bool {
if _, err := fmt.Fprintf(os.Stderr, "%s [y/N] ", msg); err != nil {
panic(err)
}
var res string
_, _ = fmt.Scanln(&res)
if strings.HasPrefix(strings.ToLower(res), "y") {
return true
}
return false
}
|
package events
import (
"time"
"github.com/bonjourmalware/melody/internal/config"
"github.com/bonjourmalware/melody/internal/events/helpers"
"github.com/bonjourmalware/melody/internal/logdata"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
)
// ICMPv6Event describes the structure of an event ... |
package base
import (
"reflect"
"strings"
"testing"
"github.com/go-test/deep"
)
func TestNewEmptyGTS(t *testing.T) {
tests := []struct {
name string
want *GTS
}{{
name: "New empty GTS",
want: >S{
ClassName: "",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Val... |
package service
import (
"errors"
"github.com/satori/go.uuid"
"zhiyuan/scaffold/internal/model"
)
func (s *Service) CreateCamera(CameraParams model.Camera_json)(result model.Camera,err error){
//数据交换
//传入DB方法
uid, _ := uuid.NewV4()
Add_Camera := model.Camera{
Camera_type:CameraParams.Camera_type,
Camera... |
package future
import (
"time"
"fmt"
)
/**
Go-简洁的并发
http://www.yankay.com/go-clear-concurreny/
*/
type Query struct {
sql chan string
result chan string
}
//执行query
func ExecQuery(q Query) {
go func() {
sql := <-q.sql
q.result <- "get:"+sql
}()
}
func Test1() {
q := Query{make(chan string,1), make(ch... |
package controllers
import (
"github.com/gin-gonic/gin"
"net/http"
)
// Controller implements handlers for web server requests.
type Controller struct {
betResponse BetResponse
}
// NewController creates a new instance of Controller
func NewController(betResponse BetResponse) *Controller {
return &Controller{
... |
package validation
import (
"fmt"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/types/aws"
)
func TestValidatePlatform(t *testing.T) {
cases := []struct {
na... |
package es
import (
"context"
"errors"
"fmt"
"log"
"os"
"gopkg.in/olivere/elastic.v5"
)
func CreateNewElasticSearchClient(ctx context.Context, url *string, sniff *bool, trace *bool) *elastic.Client {
var options []elastic.ClientOptionFunc
options = append(options, elastic.SetURL(*url))
options = append(opti... |
package tool
import (
"testing"
)
func TestGzipEncodeAndDecode(t *testing.T) {
rawData := []byte(`hello, 中新经纬客户端11月6日电 据国家发改委网站6日消息,10月30日,国家发展改革委修订发布了《产业结构调整指导目录(2019年本)》(以下简称《目录(2019年本)》)。国家发改委产业发展司负责人就《目录(2019年本)》答记者问时表示,此次修订重点包含破除无效供给、推动制造业高质量发展等四方面。鼓励类新增“人力资源与人力资本服务业”、“人工智能”、“养老与托育服务”、“家政”等4个行业。`)
encodeData ... |
package handler
import (
"mux-rest-api/domain/contact"
"mux-rest-api/domain/contact/usecase"
"net/http"
"go.mongodb.org/mongo-driver/mongo"
)
//ListContactHandler - This interface provides the object with the responsibility to handle the request to retrieve the contact list.
type ListContactHandler interface {
... |
package easygo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"runtime"
"strconv"
"strings"
"time"
)
//BuildRequest build your http request in one easy, convenient line, just return after this method.
func BuildRequest(domain string, port string, method string, endpoint string, headers m... |
package user
import (
log "github.com/sirupsen/logrus"
"oauth-server-lite/g"
)
func CreateLock(userID, clientIP string) {
rc := g.ConnectRedis().Get()
defer rc.Close()
redisKey := g.Config().RedisNamespace.Lock + userID + ":" + clientIP
_, err := rc.Do("SET", redisKey, 1, "EX", g.Config().LockTime)
if err != ... |
package main
import (
"fmt"
"math"
"sort"
)
func main() {
nums := []int{0, 0, 0}
target := 1
fmt.Println(threeSumClosest(nums, target))
}
func threeSumClosest(nums []int, target int) int {
min := math.MaxInt32
sort.Ints(nums)
for i := 0; i < len(nums)-2; i++ {
left := i + 1
right := len(nums) - 1
for... |
package main
import (
"MailService/Postgres"
"MailService/config"
"MailService/internal/Delivery"
"MailService/internal/Repository/LetterPostgres"
"MailService/internal/UseCase"
letterProto "MailService/proto"
"fmt"
"google.golang.org/grpc"
"log"
"net"
)
func main() {
lis, err := net.Listen("tcp", ":8083")... |
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2019 Datadog, Inc.
package strategy
import (
"testing"
corev1 "k8s.io/api/core/v1"
"k8s.io... |
func minSwapsCouples(row []int) int {
res:=0
for i:=0;i<len(row);i+=2{
if row[i+1]==row[i]^1{ continue }
for j:=i+2;j<len(row);j++{
if row[j] == row[i]^1 {
row[i+1], row[j] = row[j],row[i+1]
}
}
res++
}
return res
}
|
package govisitor
import (
"errors"
"fmt"
"go/ast"
"go/token"
"golang.org/x/tools/go/ast/astutil"
)
type Visitor struct{}
type Walker struct {
errs []error
f *ast.File
fset *token.FileSet
}
func (v *Visitor) Run(f ast.Node, fset *token.FileSet) []error {
walker := &Walker{
errs: []error{},
f: f.... |
package json
import (
"bytes"
"testing"
. "github.com/warpfork/go-wish"
"github.com/polydawn/refmt/tok/fixtures"
)
// note: we still put all tests in one func so we control order.
// this will let us someday refactor all `fixtures.SequenceMap` refs to use a
// func which quietly records which sequences have tes... |
package util
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"projja_telegram/model"
"strconv"
)
type BotUtil struct {
Message *MessageData
Bot *tgbotapi.BotAPI
Updates chan tgbotapi.Update
}
type MessageData struct {
From *tgbotapi.User
Chat *tgbotapi.Chat
}
func TgUserToModelUser(d... |
package main
import (
"fmt"
"io"
"os"
smartling "github.com/Smartling/api-sdk-go"
"github.com/reconquest/hierr-go"
)
func doProjectsLocales(
client *smartling.Client,
config Config,
args map[string]interface{},
) error {
var (
project = config.ProjectID
short, _ = args["--short"].(bool)
source, _ =... |
package main
import (
"encoding/json"
"io/ioutil"
"path"
)
type PassReader interface {
ReadPassword() (string, error)
}
type file_passer struct {
filename string
}
func (f *file_passer) ReadPassword() (string, error) {
cont, err := ioutil.ReadFile(f.filename)
if err != nil {
return "", err
}
var Conf str... |
package test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/exitcode"
"github.com/str... |
package client
import (
"fmt"
"github.com/MagalixTechnologies/core/logger"
"runtime"
)
// Recover recover from panic used to send logs before exiting
func (client *Client) Recover() {
tears := recover()
if tears == nil {
return
}
message := fmt.Sprintf(
"PANIC OCCURRED: %v\n%s\n", tears, string(stackTrace... |
package server
import (
"fmt"
"os"
"os/exec"
"github.com/marcomilon/ezphp/internals/output"
)
type Args struct {
Php string
Host string
Public string
}
func Run(args Args) {
output.Info("Command: " + args.Php + " -S " + args.Host + " -t " + args.Public + "\n")
output.Info("Your server url is: " + "htt... |
package postedition
import "time"
//PostPub is post what will be publiched and displayable
type PostPub struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Body string `json:"body"`
Nick string `json:"nick"`
Avatar string `json:"avatar"`
Likes ... |
package leetcode
import (
"container/list"
"fmt"
)
type trap struct{}
// TODO 暴力
// TODO 哈希
// TODO 双指针
// 栈
func (t trap) Do(height []int) int {
stack := list.New()
stack.PushBack(0)
var ret int
for i := 1; i < len(height); i++ {
if height[i] > height[i-1] {
for stack.Len() != 0 {
last := stack.... |
package main
import (
"fmt"
"os"
"gopkg.in/mgo.v2"
)
type Mongo struct {
host string
port string
user string
pass string
dbname string
session *mgo.Session
db *mgo.Database
}
var (
mongodbServer string = os.Getenv("MONGODB_HOST") //"dds-2ze087e692f063041.mongodb.rds.aliyuncs.com"
mon... |
// 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 raw_client
import (
"context"
)
type GetPreviewAppDeployRequest struct {
Apps []string `json:"apps"`
}
type GetPreviewAppDeployResponse struct {
Apps []GetPreviewAppDeployResponseApp `json:"apps"`
}
type GetPreviewAppDeployResponseApp struct {
App string `json:"app"`
Status string `json:"status"`
}
... |
// Copyright 2009 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 bytes implements functions for the manipulation of byte slices.
// It is analogous to the facilities of the strings package.
// this is copy from `b... |
package main
import (
"encoding/json"
"net/http"
"strconv"
"net/url"
"fmt"
"log"
"github.com/Bobochka/thumbnail_service/lib"
"github.com/Bobochka/thumbnail_service/lib/service"
"github.com/Bobochka/thumbnail_service/lib/transform"
)
type App struct {
service *service.Service
}
type params struct {
url... |
// A package that does modular arithmetic.
//
// Doesn't use a single % operator or any math library functions.
// This is more for experience than for actual use. There is also a variation of this for big integers,
// which can be found in the bigmod package (github.com/deanveloper/modmath/bigmod)
package bigmod
impo... |
package gomonkey
import (
"fmt"
"reflect"
)
type FuncPara struct {
target interface{}
matchers []Matcher
behaviors []ReturnValue
}
type PatchBuilder struct {
patches *Patches
funcPara FuncPara
}
func NewPatchBuilder(patches *Patches) *PatchBuilder {
funcPara := FuncPara{target: ... |
// This file was generated for SObject Publisher, API Version v43.0 at 2018-07-30 03:47:25.940649177 -0400 EDT m=+12.283716535
package sobjects
import (
"fmt"
"strings"
)
type Publisher struct {
BaseSObject
DurableId string `force:",omitempty"`
Id string `force:",omitempty"`
IsSalesforce ... |
package es
import (
"fmt"
"strconv"
"strings"
. "github.com/Dataman-Cloud/omega-es/src/util"
"github.com/Jeffail/gabs"
log "github.com/cihub/seelog"
"github.com/gin-gonic/gin"
)
func SearchIndex(c *gin.Context) {
body, err := ReadBody(c)
if err != nil {
log.Error("searchindex can't get request body")
Re... |
package main
import ("fmt")
type Rect struct {
l, b float64
}
func calArea (R* Rect) (float64){
return R.l*R.b
}
func (R* Rect) calArea() float64 {
return R.l*R.b
}
func main() {
var R1 Rect
R1.l = 10
R1.b = 20
area := calArea(&R1)
fmt.Println(area)
area = R1.calArea()
fmt.Pri... |
package main
import (
"fmt"
)
func main() {
dy := map[string]int{
"Sunday": 9,
"Monday": 10,
"Tuesday": 11,
"Wednesday": 12,
"Thursday": 13,
"Friday": 14,
"Saturday": 15,
"Mayday": 16,
}
fmt.Println(dy)
fmt.Println(dy["Sunday"])
fmt.Println(dy["Holyday"])
v, ok := dy["Holyday"]... |
package main
import(
"fmt"
"time"
)
func pinger(c chan <- string){ //<- makes it unidirectional (only send , no receive)
for i :=0; ;i++{
c <- "ping"
time.Sleep(time.Second*3)
}
}
func ponger(c1 chan string){
for i :=0; ;i++{
c1 <- "pong"
time.Sleep(time.Second*5)
}
}
func printer(c,c1 chan ... |
package app
/*
主要用来格式化输入参数,用来防止sql注入,xss攻击等
*/
import (
"github.com/comdeng/HapGo/hapgo/conf"
"github.com/comdeng/HapGo/hapgo/logger"
_html "github.com/comdeng/HapGo/lib/html"
// "log"
"net/http"
"strings"
"sync"
"time"
)
const trimReg = " \t\r\n\x0b\v"
const inputConfKey = "hapgo.input"
var replacer = str... |
/*
* @lc app=leetcode.cn id=297 lang=golang
*
* [297] 二叉树的序列化与反序列化
*/
package main
import (
"fmt"
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// @lc code=start
type Codec struct {
l []string
str strings.Builder
}
func Constructor() Codec {
return Codec{}
}... |
package main
import(
"fmt"
)
func longestValidParentheses(s string) int {
if len(s) < 2 {
return 0;
}
maxLength := 0
var stack = make([]int, len(s) + 1)
stackIndex := -1
stackIndex++
stack[stackIndex] = -1
var tmpStr string
for i, tmpChar := range s[:] {
tmpStr = string(tmpChar)
if tmpStr == "("... |
package sqly
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
type dbDriver int8
const (
driverMysql dbDriver = 1
driverPostgresql dbDriver = 2
driverOthers dbDriver = 99
)
var argFmtFunc argFormat
// SqlY struct
type SqlY struct {
db *sql.DB
driver dbDriver
}
// Option sqly config... |
package hookEvent
import (
"github.com/aws/aws-lambda-go/events"
)
type Credential struct {
Category string `json:"category"` // bitbucket:oauth
Key string `json:"key"`
Secret string `json:"secret"`
}
type Event struct {
SourceBranch string `json:"sourceBranch"`
DestinationBranch string ... |
package stun
import "testing"
func TestParseURI(t *testing.T) {
for _, tc := range []struct {
name string
in string
out URI
}{
{
name: "default",
in: "stun:example.org",
out: URI{
Host: "example.org",
Scheme: Scheme,
},
},
{
name: "secure",
in: "stuns:example.org",
... |
package main
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"github.com/go-redis/redis"
)
// Server main object
type Server struct {
port int
redisDB *redis.Client
getMatch *regexp.Regexp
setMatch *regexp.Regexp
}
// NewServer creates a new server instance
func NewServer(port int, redisHost string, r... |
package main
import "fmt"
//定义变量的形式为 var 变量名 变量类型 在定义的时候,如果没有进行初始化操作,会有一个默认值
func main1(){
var a int
a = 10
a = a+25
fmt.Print(a)
}
/**
计算圆的周长和面积
*/
func main2(){
//使用;=的方式定义变量
PI:=3.1415926
r:=2.5
l:=2*PI*r;
fmt.Println(l)
s:=PI*r*r
fmt.Print(s)
}
func main3(){
//自动推断类型
//w:=5.0 //float64
//... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.