text stringlengths 11 4.05M |
|---|
package plugins
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseBar(t *testing.T) {
p := NewTbasePlugin()
actualCurrentStep, actualTotolStep, err := p.ParseBar("30, 100")
assert.Equal(t, uint32(30), actualCurrentStep)
assert.Equal(t, uint32(100), actualTotolStep)
_, _, err = p.ParseBar... |
/*
* Copyright 2018 American Express
*
* 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... |
// time: o(2n), space: o(2n)
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
copied := make(map[*Node]*Node)
res := &Node{}
cur := head
curRes := res
for cur != nil {
c := &Node{cur.Va... |
package main
import (
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter11/discovery"
consul "github.com/hashicorp/consul/api"
)
func main() {
config := consul.DefaultConfig()
config.Address = "localhost:8500"
// faked name and port for example
cli, err := discovery.NewClient(config, "l... |
/*
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 main
import (
"fmt"
"sort"
)
//Person type
type Person struct {
First string
Last string
Age int
Sayings []string
}
// ByAge implements sort.Interface for []Person based on the Age field.
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) ... |
package main
import (
"fmt"
"math"
)
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4) // default value
}
func main() {
hypot := func(a, b float64) float64 {
return math.Hypot(a, b)
}
fmt.Println(hypot(5, 12))
fmt.Println(compute(hypot))
fmt.Println(compute(math.Pow)) // 3*3*3*3
}
|
package cspec
import "fmt"
// Number is usually a hex value
type Number struct {
Value string // should this be an actual numeric?
}
func (n *Number) String() string {
return fmt.Sprintf("{{.FormatNumber \"%s\" }}", n.Value)
}
|
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net"
"os"
"strings"
"sync"
"time"
)
const HEARTBEAT = 10
// this backend server support reft as consensus model for distributed backend
// -------------------------------------------------------- //
// Reft implementation //
// machin... |
package main
import (
"fmt"
)
func main() {
totalInputs := 0
ans := 0
fmt.Scanf("%d", &totalInputs)
//fmt.Println(totalInputs)
newArr := make([]int, totalInputs)
for j := 0; j < totalInputs; j++ {
//fmt.Print()
fmt.Scanf("%d : ", &newArr[j])
}
for k := 0; k < len(newArr); k++ {
ans = 0
for... |
package schedulerd
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/sensu/sensu-go/backend/store"
"github.com/sensu/sensu-go/types"
)
// ResourceSync interface for structs that fetch resources
type ResourceSync interface {
Sync(ctx context.Context) error
}
// SynchronizeChecks fetches checks from t... |
package model
import (
"github.com/KubeOperator/KubeOperator/pkg/model/common"
uuid "github.com/satori/go.uuid"
)
type Message struct {
common.BaseModel
ID string `json:"-"`
Title string `json:"title"`
Sender string `json:"sender"`
Content string `json:"content"`
Type string `json:"type"`
Level ... |
package handlers
import (
"Site1/helpers"
"Site1/models"
"html/template"
"net/http"
)
func RegisterHandler(write http.ResponseWriter, request *http.Request) {
checkUser := helpers.GetUserCookie(request)
if len(checkUser) > 0 {
redirectTarget := "/dashboard"
http.Redirect(write, request, redirectTarget, 302... |
package main
import (
"log"
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"net/http"
"strings"
"encoding/json"
"strconv"
)
type Abc int
type First int
type Third int
var generic map[string]interface{}
var askvalue[2] float64
var firstperc,secperc,totamount int
var number[2] int
var amount[2] float64
var symbol[... |
package dht
import (
"context"
"crypto/rand"
"testing"
"time"
ci "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto"
u "gx/ipfs/QmNohiVssaPw3KVLZik59DBVGTSm2dGvYT9eoXt5DQ36Yz/go-ipfs-util"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
routing "gx/ipfs/QmRjT... |
package app
import (
"errors"
"html/template"
"io"
"github.com/labstack/echo"
"github.com/seiichi3141/gompleapp/app/helper"
)
// Template struct
type Template struct {
templates map[string]*template.Template
}
// Render render template
func (t *Template) Render(w io.Writer, name string, data interface{}, c ec... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//498. Diagonal Traverse
//Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the be... |
package tmpl2
import (
"testing"
)
func Test_findPeakElement(t *testing.T) {
type args struct {
nums []int
}
tests := []struct {
name string
args args
ok map[int]bool
}{
{
name: "one peak1",
args: args{
nums: []int{1, 2, 3, 1},
},
ok: map[int]bool{
2: true,
},
},
{
name:... |
package handlers
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/clems4ever/go-graphkb/internal/client"
"github.com/clems4ever/go-graphkb/internal/knowledge"
"github.com/clems4ever/go-graphkb/internal/metrics"
"github.com/clems4ever/go-graphkb/internal/sources"
"github.com/prome... |
package reverseinteger
import (
"math"
"strconv"
"strings"
)
// Reverse inverses integer number
func Reverse(numberToReverse int) int {
numberAsString := strconv.Itoa(numberToReverse)
var resultAsSlice []string
var endIndex int
if strings.HasPrefix(numberAsString, "-") {
endIndex = 1
resultAsSlice = appe... |
// Copyright 2017 Yahoo Holdings Inc.
// Licensed under the terms of the 3-Clause BSD License.
package provider
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/tools/c... |
package check
import (
"fmt"
"github.com/MintegralTech/juno/debug"
"github.com/MintegralTech/juno/document"
"github.com/MintegralTech/juno/index"
"github.com/MintegralTech/juno/marshal"
)
type AndChecker struct {
c []Checker
aDebug *debug.Debug
}
func NewAndChecker(c []Checker) *AndChecker {
if c == nil... |
package imjasonh
import (
"appengine"
"appengine/datastore"
"appengine/user"
"fmt"
"html/template"
"net/http"
"net/url"
"time"
)
type Shortcut struct {
URL string
User string
Created time.Time
}
var tmpl = template.Must(template.New("form").Parse(`
<html><body>
<form action="/go" method="POST">
... |
package functions
// Insert a value at an index
func (ss SliceType) Insert(index int, values ...ElementType) SliceType {
if index >= ss.Len() {
return SliceType.Extend(ss, SliceType(values))
}
return SliceType.Extend(ss[:index], SliceType(values), ss[index:])
}
|
// Copyright 2017 The OpenSDS Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... |
// Copyright (c) 2018 Palantir Technologies. All rights reserved.
//
// 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 require... |
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/stianeikeland/go-rpio/v4"
)
var (
pin = rpio.Pin(10) // Physical pin 19 on the RPi
)
func main() {
setupCloseHandler()
if err := rpio.Open(); err != nil {
fmt.Printf("error opening the rpio connection: %v\n", err)
os.Exit(1)
}
... |
package 二分
// ----------------------------------- 方法1: 暴力 -----------------------------------
// 执行用时:4 ms, 在所有 Go 提交中击败了 99.07% 的用户
// 内存消耗:3.8 MB, 在所有 Go 提交中击败了 100.00% 的用户
func searchMatrix(matrix [][]int, target int) bool {
rows, cols := getRowsAndCols(matrix)
for i := 0; i < rows; i++ {
for t := 0; t < co... |
package main
import (
"fmt"
"io/ioutil"
"strings"
)
type vFile struct {
name string
path string
content string
uContent string
}
//this file has file structure and other utility methods like reading and writing to files.
func (vf vFile) print(modified bool) {
fmt.Println("********************** ",... |
package input
import "fmt"
type ErrDecode struct {
s string
}
func (e ErrDecode) Error() string {
return fmt.Sprintf("decode error: %v", e.s)
}
|
package oiio
import (
"errors"
"fmt"
"reflect"
"unsafe"
)
// Given an ImageSpec, a slice is allocated to the size that
// is able to contain the pixels of the ImageSpec dimensions.
// The TypeDesc determines what format the pixels will be stored in.
// Returns the slice, casted to an interface.
func allocatePixel... |
package main
import (
"flag"
"github.com/the-spectator/go-pincode-scanner/service"
)
func main() {
fileName := flag.String("file", "", "File name")
rate := flag.Int("rl", 50, "Rate Limit")
flag.Parse()
service.DoPincodeFetchJob(*fileName, *rate)
}
|
package dbtools
// podstawowa obsluga ORM bazy danych
// selecty z bazy
import (
"log"
//"time"
"mstr"
)
func GetAccesDataUser(Id string) (results []mstr.AccesInfo) {
rows, err := DB.Table("UPRAWNIENIA_DOMYSLNE").Select(`UPRAWNIENIA_DOMYSLNE.ID_UPRAWNIENIA AS ID_UPRAWNIENIA,
UPRAWNIENIA_DOMYSLNE.ID_RODZICA A... |
package auth
import (
"fmt"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
)
const (
UserId = "USER_123456"
SecretKey = "secret"
SigningMethod = "HS512"
)
type LoginForm struct {
UserName string `json:"username" form:"username" query:"username" validate... |
package constants
var (
DefaultHTTPOpenPort = "80"
DefaultHTTPSOpenPort = "443"
UseHostPort = false
UseIPAddress = ""
ServiceCidr = ""
DefaultServiceVersion = "v0"
IstioVersion = "1.1.7"
IstioGateway = "ingressgateway"
IstioMeshConfigKe... |
package entity
import (
"time"
)
type UmsPermission struct {
Id int64 `json:"id" db:"id"`
Pid int64 `json:"pid" db:"pid"`
Name string `json:"name" db:"name"`
Value string `json:"value" db:"value"`
Icon string `json:"icon" db:"icon"`
Type int `json:"type" d... |
/*
The proceeding file was copied from derui's go-threes program. All credit goes to derui for creating this.
*/
package libthrees
import (
"fmt"
)
type Accessor interface {
X() int
Y() int
}
type ValueDefiner interface {
Accessor
Value() Three
}
type Pos struct {
x int
y int
}
func (t *Pos) X() int {
retu... |
package main
import (
"context"
"errors"
"fmt"
"log"
"net/url"
"os"
"strings"
"time"
"github.com/google/go-github/v32/github"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/s... |
package divide_conquer
type ListNode struct {
Val int
Next *ListNode
}
func mergeKLists(lists []*ListNode) *ListNode {
if len(lists) == 0 {
return nil
}
return help23(lists, 0, len(lists)-1)
}
func help23(lists []*ListNode, start, end int) *ListNode {
if start == end {
return lists[start]
}
if start > e... |
// 记录请求日志
package main
import "net/http"
import "time"
import "fmt"
// 打印日志
func runLogging(logs chan string) {
for log := range logs {
fmt.Println(log)
}
}
// 包装日志记录方法
func wrapLogging(f http.HandlerFunc) http.HandlerFunc {
// 打开日志通道
logs := make(chan string, 10000)
// 开启协程记录日志
go runLo... |
package main
type Area struct {
a, b *Point
}
func (area *Area) Width() int {
return area.b.x - area.a.x
}
func (area *Area) Height() int {
return area.b.y - area.a.y
}
func (area *Area) Contains(point *Point) bool {
if point.x >= area.a.x && point.x <= area.b.x {
if point.y >= area.a.y && point.y <= ar... |
package main
import "fmt"
import "net/http" // package untuk web server
import "encoding/json"
type Siswa struct {
Nm_siswa string `json:"nm_siswa"`
Kelas string `json:"kelas"`
Umur int `json:"umur"`
}
func getSiswa(res http.ResponseWriter, req *http.Request) {
// untuk menentukan header response
res.Heade... |
package main
import (
"flag"
"log"
"net/http"
"strconv"
"github.com/julienschmidt/httprouter"
"github.com/yalay/OpenCC-Server/controllers"
)
var tplPath string
var listenPort int
func init() {
flag.StringVar(&tplPath, "t", "views", "frontend template files path")
flag.IntVar(&listenPort, "p", 8015, "listen ... |
package model
type Weather struct {
Current struct {
TempC float64 `json:"temp_c"`
} `json:"current"`
Forecast struct {
Forecastday []struct {
Date string `json:"date"`
Day struct {
MaxtempC float64 `json:"maxtemp_c"`
MintempC float64 `json:"mintemp_c"`
} `json:"day"`
} `json:"forecastday"`
... |
package main
import (
"github.com/bar41234/bar_book_service/datastore"
"github.com/bar41234/bar_book_service/service"
"github.com/gin-gonic/gin"
)
func main() {
err := setup()
if err != nil {
panic(err)
}
router := gin.Default()
//Adding middlewares
middlewares(router)
//Registering the routes
service.... |
package account
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"strings"
"sync"
"time"
"github.com/cloudfly/ecenter/pkg/store"
"github.com/cloudfly/ecenter/pkg/types"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/prometheus/common/log"
)
// Chan 代表接收渠道,同 github.com/cloudfly/ecenter.... |
package queue
import (
"fmt"
"testing"
)
func TestQueue(t *testing.T) {
queue := NewQueue()
queue.Offer("a")
queue.Offer("b")
queue.Offer("c")
fmt.Println("size:", queue.Size())
fmt.Println("peek:", queue.Peek())
fmt.Println("all:", queue.GetAll())
v := queue.Poll()
fmt.Println("poll: value", v)
fmt.Print... |
package main
import (
"fmt"
"net"
"regexp"
"strings"
"sync"
"time"
"github.com/miekg/dns"
)
var addressRegex = regexp.MustCompile("([\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3})$")
var addressMap = map[string]string{}
var updateMutex = new(sync.Mutex)
// updateAddressCache updates the dns map of real na... |
package errors
import (
"bytes"
"fmt"
"io"
"reflect"
"runtime"
"strings"
"testing"
)
func TestStackFormat(t *testing.T) {
defer func() {
err := recover()
if err != 'a' {
t.Fatal(err)
}
e, expected := Errorf("hi"), callers()
bs := [][]uintptr{e.stack, expected}
if err := compareStacks(bs[0]... |
package cfmysql_test
import (
"code.cloudfoundry.org/cli/plugin/pluginfakes"
"errors"
. "github.com/andreasf/cf-mysql-plugin/cfmysql"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("SshRunner", func() {
var cliConnection *pluginfakes.FakeCliConnection
var sshRunner SshRunner
servi... |
package main
import "testing"
func TestQuickUnionNew(t *testing.T) {
for _, tc := range []struct {
name string
n int
err error
ids []int
}{
{
name: "empty",
err: ErrNotPositiveN,
},
{
name: "n is negative number",
n: -1,
err: ErrNotPositiveN,
},
{
name: "n is positive n... |
// 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 statsd
import (
"errors"
"fmt"
"math/rand"
"net"
"strings"
"sync"
"time"
)
// define errors
var (
Err_NotConnected = errors.New("can't send stats, not connected to StatsD server")
Err_InvalidCount = errors.New("count is less than zero")
Err_InvalidSampleRate = errors.New("sample rate large... |
package problem0637
// TreeNode 树节点
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func averageOfLevels(root *TreeNode) []float64 {
result := []float64{}
if root == nil {
return result
}
queue := []*TreeNode{root}
for len(queue) > 0 {
cnt := len(queue)
sum := 0
for i := 0; i < cnt;... |
// Package sonarr implements the sonarr webhook schema.
//
// This is grabbed from https://github.com/Sonarr/Sonarr/wiki/Webhook-Schema,
// and converted to Golang by using https://app.quicktype.io.
package sonarr
import "encoding/json"
func UnmarshalSonarrEvent(data []byte) (SonarrEvent, error) {
var r SonarrEvent... |
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"sync"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
func getK8sConfig() *rest... |
package mem
import (
_"fmt"
_"encoding/json"
"sysmonitor/common"
"sysmonitor/profile"
"github.com/shirou/gopsutil/mem"
)
func MemMonitor() string {
mem_info, _ := mem.VirtualMemory()
mem_swap, _ := mem.SwapMemory()
mem_status := new(profile.MemStatus)
mem_status.Mem.Total = mem_info.Total/1024/1024
mem_... |
package main
import "fmt"
func PrintVal(val int) {
fmt.Println("Value is:", val)
}
func main() {
val := 10
defer PrintVal(val)
defer PrintVal(val + 1)
defer PrintVal(val + 2)
val = 20
fmt.Println("Main function done with val:", val)
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
package service
import (
"net/http"
"time"
"pricingengine/service/app"
"pricingengine/service/rpc"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
// Start begins a chi-Mux'd net/http server on port 3000
func Start() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Timeout(5 *... |
package endpoints
import (
"encoding/json"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
adm "github.com/ebikode/eLearning-core/domain/admin"
app "github.com/ebikode/eLearning-core/domain/application"
aud "github.com/ebikode/eLearning-core/domain/authd_device"
usr "github.com/ebikode/eLearning-core/domain/u... |
package main
import (
"fmt"
)
// 无参无返回值函数
func test01() {
fmt.Println("test01...")
}
// 无参有一个返回值函数
func test02() (result int) {
result = 123
return
}
// 无参有多个返回值函数
func test03() (num int, str string) {
num = 99
str = "Hello go"
return
}
// 有参有返回值函数
func test04(a int) (num int, str string) {
num = a + 1
st... |
package main
import (
"time"
"log"
"strings"
"strconv"
"bytes"
"encoding/json"
"io/ioutil"
"encoding/binary"
"net/http"
_ "net/http/pprof"
"git.leaniot.cn/publicLib/go-modbus"
"gopkg.in/yaml.v2"
"errors"
)
var config Config
type Table struct {
Define string `json:"define"`
Unit string `json:"unit"`
... |
package main
import (
"go/ast"
"go/parser"
"go/token"
"strings"
"unicode"
)
type imp struct {
name string
pkg string
}
// validCode validates the source code data.
func validCode(b []byte) (bool, string, error) {
fset := token.NewFileSet()
// Parse the source code.
f, err := parser.ParseFile(fset, "", b, ... |
package apigen
import (
"fmt"
)
var postLibFn string
// WritePostAPIToLib - This writes the post api libary defination into lib file
func WritePostAPIToLib(apimodel API) {
postLibFn = ""
createPostAPILibFuncStart(apimodel)
createPostAPILibFuncParams(apimodel)
createPostAPILibFuncBody(apimodel)
ReplaceFileConte... |
package utils
import (
"os"
"path/filepath"
"sync"
)
const (
ConfFile = "conf.yaml"
ConfDir = "conf"
)
var (
once sync.Once
confDir string
)
func GetWorkDir() string {
once.Do(func() {
wd, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
confDir = "./"
}
confDir = wd
})
return ... |
package main
import (
"flag"
"fmt"
"log"
"net/rpc"
"os"
"strconv"
"strings"
"time"
"github.com/janelia-flyem/drmaa"
"github.com/janelia-flyem/drmaa/gestatus"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/server"
"github.com/janelia-flyem/dvid-cluster/node"
)
var (
// Display usa... |
package helpers
import (
"github.com/martinyonathann/bookstore_items-api/datasource/mysql/users_db"
"github.com/martinyonathann/bookstore_items-api/utils/errors"
)
const (
queryValidate = "SELECT COUNT(*) FROM items where book_name = ? AND year_created = ?;"
)
func Validate(bookName, year_created string) (int, *e... |
package db
import (
"encoding/json"
"time"
"github.com/VolticFroogo/Animal-Pictures/models"
"github.com/zemirco/uid"
)
// GetHotPosts will get the respective hot posts for a given page.
func GetHotPosts(page int) (posts []models.Post, err error) {
rows, err := db.Query("SELECT P.uuid, P.title, P.description, P.... |
package root
import (
"fmt"
"os"
"github.com/jenkins-x/jx/pkg/cmd/clients"
"github.com/jenkins-x/jx/pkg/cmd/opts"
"github.com/jenkins-x-labs/helmboot/pkg/cmd"
"github.com/jenkins-x-labs/jwizard/pkg/cmd/create"
token "github.com/jenkins-x-labs/step-parse-git-credentials-token/cmd/root"
goreleaser "github.com/... |
package smtcp
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewRequest(t *testing.T) {
params := NewParams()
p1, p2 := NewPipe()
defer p1.Close()
defer p2.Close()
request := NewRequest("request_name", params, p1)
actual := request.Envelope()
expected := "\f\x00\x00\x00request_name\x0... |
package xml
import (
"encoding/xml"
"io"
"strings"
)
func GetStartTag(bytes []byte) (string, error) {
decoder := xml.NewDecoder(strings.NewReader(string(bytes)))
for {
t, err := decoder.Token()
if err != nil {
if err == io.EOF {
return "", nil
}
return "", err
}
if se, ok := t.(xml.StartEle... |
package integration_test
import (
"github.com/cloudfoundry/libbuildpack/cutlass"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("a staticfile app with custom error pages", func() {
var app *cutlass.App
AfterEach(func() {
if app != nil {
app.Destroy()
}
app = nil
})
BeforeEa... |
package main
import "fmt"
func maximalSquare(matrix [][]byte) int {
//使用dp转移
//dp[i][j] = min(dp[i-1,j-1],dp[i-1],[j],dp[j]) +1
rows := len(matrix)
if rows <= 0 {
return 0
}
cols:= len(matrix[0])
dp:= make([][]int,len(matrix))
len := 0
//初始化dp数组
for i:=0;i<rows;i++{
dp[i] = make([]int,cols)
for j :=0... |
package controllers
import (
"github.com/gin-gonic/gin"
"spapp/src/handlers/friend"
)
func FriendController(router *gin.RouterGroup) {
apis := router.Group("/friend")
{
apis.POST("/make-friend", friend.MakeFriendHandle)
apis.POST("/get-friends", friend.GetFriendsHandle)
apis.POST("/get-common-friends", fr... |
// BSD 3-Clause License
//
// Copyright (c) 2020, Kingsgroup
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, thi... |
//+build test
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package kubernetes
import (
"context"
"encoding/json"
"log"
"os/exec"
"strings"
"time"
"github.com/Azure/aks-engine/test/e2e/kubernetes/util"
"github.com/pkg/errors"
)
// Config represents a kuberne... |
package main
import (
"fmt"
"provider_probe/src"
)
const timerPort string = "8090"
func main() {
email := "example@example.com"
fmt.Print(src.SendRequest(email))
} |
/*
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 smallpng
import (
"image/color"
"math"
)
type ColorSpace int
const (
CIELAB ColorSpace = iota
RGB
)
const labAlphaScale = 128.0
func (c ColorSpace) toColor(v colorVector) color.Color {
switch c {
case RGB:
return color.RGBA{
R: uint8(v[0] * 255.999),
G: uint8(v[1] * 255.999),
B: uint8(v[2]... |
package global
import (
"reflect"
"testing"
"github.com/sirupsen/logrus"
)
func TestInit(t *testing.T) {
tests := []struct {
name string
wantErr bool
}{
{"base-case", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := Init(); (err != nil) != tt.wantErr {
t.Err... |
// Copyright (C) 2020 Cisco Systems Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agr... |
package fs
import (
"fmt"
"sync"
"runtime"
"defs"
"limits"
"mem"
)
const bdev_debug = false
// A block has a lock, since, it may store an inode block, which has several
// inodes, and we need to ensure that hat writes aren't lost due to concurrent
// inode updates. The inode code is careful about releasing l... |
package http
import (
"fmt"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"log"
"net/http"
)
type Result struct {
Title string
Content string
}
type HttpWeb struct {
URLPrefix string
}
var Web HttpWeb = HttpWeb{
}
func (this *HttpWeb)registerWebRequest(m *martini.ClassicMartini, path ... |
package scraper
import (
"fmt"
"github.com/znconrad5/fantasyfootball"
"time"
)
func NewNflScraper(positions []fantasyfootball.Position, season int, startWeek int, endWeek int) *Scraper {
return &Scraper{
&nflUrlGenerator{
positions: positions,
season: season,
startWeek: startWeek,
endWeek: endW... |
package structs
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
pb "github.com/sonm-io/core/proto"
)
func TestNewInMemoryStorage_GetOrders_compareSupRating(t *testing.T) {
cases := []struct {
r1 int64
r2 int64
mustMatch bool
message string
}{
{
r1: 1,
r2: ... |
// Copyright 2019 Yunion
//
// 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 writi... |
package mongodb
import (
"context"
"fmt"
"log"
"sync"
"time"
"github.com/markus-azer/products-service/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
const connected = "Successfully connected to database: "
//MongoDatast... |
package main
import (
"flag"
"log"
"net/http"
"net/http/httputil"
"net/url"
"runtime"
"time"
)
var (
addr = flag.String("http", ":80", "")
next = flag.String("next", "http://httpbin.org", "")
)
func init() {
flag.Parse()
runtime.GOMAXPROCS(runtime.NumCPU())
}
func NewServer(u *url.URL) *http.Server {
h ... |
package helper
import (
"io/ioutil"
"os"
"testing"
"github.com/devspace-cloud/devspace/pkg/util/fsutil"
"gotest.tools/assert"
)
func TestCreateTempDockerfile(t *testing.T) {
//Create tempDir and go into it
dir, err := ioutil.TempDir("", "testDir")
if err != nil {
t.Fatalf("Error creating temporary directo... |
package api
import (
"encoding/json"
"io"
"net/http"
"strings"
"github.com/gorilla/mux"
)
//UserSignUpRequest encapuslates the signup request
type UserSignUpRequest struct {
UserName string
Email string
Password string
}
//UserSignUpResponse encapsulates the Signup response
type UserSignUpResponse struct... |
package release
import (
"crypto/sha256"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"github.com/ExploratoryEngineering/reto/pkg/toolbox"
)
// NewFileVersions checks that the binaries/artifacts are changed since last
// release. This ignores the common artifacts (with ID set to '-') and will
// only ch... |
package main
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test_areYouSureTooApplyChanges(t *testing.T) {
type args struct {
changes int
keeps int
acceptedChanges int
}
tests := []struct {
name string
args args
want bool
}{
{
name: "refuse de supprimer tous le... |
package logging
import (
"bufio"
"bytes"
"github.com/stretchr/testify/assert"
"testing"
)
func TestLogging_InterfaceImplementation_StackDriver(t *testing.T) {
var _ Logging = StackdriverLogger{} // Verify that T implements I.
var _ Logging = (*StackdriverLogger)(nil) // Verify that *T implements I.
}
fun... |
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"text/template"
)
type ApiResponsePods struct {
Items []ApiResponsePodItems `json:"items"`
}
type ApiResponsePodItems struct {
Metadata ApiResponsePodItemMetadata `json:"metadata"`
Spec ApiResponsePod... |
package provider
import (
er "github.com/lucasvmiguel/goauth/auth/errors"
res "github.com/lucasvmiguel/goauth/auth/resource"
"github.com/lucasvmiguel/goauth/token"
"fmt"
)
//Map is a provider to maintain tokens/users
type Map struct {
mapAccessT map[string]*res.User
mapRefreshT map[string]*res.User
}
//New c... |
package orders
import (
"github.com/gin-gonic/gin"
)
func List(c *gin.Context) {
orders := Find(0, 25, nil)
c.JSON(200, orders)
}
func Create(c *gin.Context) {
o := Order{}
err := c.BindJSON(&o)
if err != nil {
// c.JSON(400, "JSON format is not correct")
c.JSON(400, err.Error... |
// +build OMIT
package sample
//START OMIT
func DoSomethingThatMightPanic() (err error) {
defer func() {
if perr := recover(); perr != nil {
err = perr
}
}()
err = externalpkg.OMGPanic()
return err
}
//END OMIT
|
// Copyright 2016 The G3N 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 gui
import (
"github.com/hecate-tech/engine/window"
)
/***************************************
Slider
+-----------------------------... |
package main
import (
"fmt"
"sort"
)
//------------------------------------------------------------------------------
// problem 2
func maxWidthOfVerticalArea(points [][]int) int {
N := len(points)
if N == 0 {
return 0
}
x := make([]int, N)
for i := 0; i < N; i++ {
x[i] = points[i][0]
}
sort.Ints(x)
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.