blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 4
108
| path
stringlengths 2
210
| src_encoding
stringclasses 12
values | length_bytes
int64 13
5.82M
| score
float64 2.52
5.22
| int_score
int64 3
5
| detected_licenses
listlengths 0
161
| license_type
stringclasses 2
values | detected_licenses_right
listlengths 0
161
| license_type_right
stringclasses 2
values | text
stringlengths 13
6.48M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a1cff90dbc46a26463d545478dae9117cd25664
|
Go
|
wzshiming/gen
|
/route/request.go
|
UTF-8
| 7,948 | 2.578125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package route
import (
"fmt"
"sort"
"github.com/wzshiming/gen/spec"
)
func (g *GenRoute) generateRequestsVar(name string, reqs []*spec.Request) error {
for _, req := range reqs {
if req.Ref != "" {
req = g.api.Requests[req.Ref]
}
if req.Type == nil {
continue
}
g.buf.WriteFormat(`// requests %s %s.%s
var %s `, req.Type.PkgPath, name, req.Name, g.getVarName(req.Name, req.Type))
g.Types(req.Type)
g.buf.WriteString("\n")
}
return nil
}
func (g *GenRoute) generateRequest(req *spec.Request, errName string) error {
if req.Ref != "" {
req = g.api.Requests[req.Ref]
}
vname := g.getVarName(req.Name, req.Type)
switch req.In {
case "none":
// No action
case "middleware":
midds := []*spec.Middleware{}
for _, midd := range g.api.Middlewares {
if len(midd.Responses) == 0 {
continue
}
resp := midd.Responses[0]
if resp.Ref != "" {
resp = g.api.Responses[resp.Ref]
}
if resp.Name != req.Name {
continue
}
if resp.Type.Ref != req.Type.Ref {
continue
}
midds = append(midds, midd)
}
switch len(midds) {
default:
g.buf.WriteFormat(`
// Permission middleware undefined %s.
`, req.Name)
case 1:
midd := midds[0]
name := g.getMiddlewareFunctionName(midd)
g.buf.WriteFormat(`
// Permission middlewares call %s.
%s, %s = %s(`, midd.Name, vname, errName, name)
if midd.Type != nil {
g.buf.WriteString(`s, `)
}
g.buf.WriteFormat(`w, r)
if %s != nil {
return
}
`, errName)
}
case "security":
secus := []*spec.Security{}
secuKey := make([]string, 0, len(g.api.Securitys))
for k := range g.api.Securitys {
secuKey = append(secuKey, k)
}
sort.Strings(secuKey)
for _, k := range secuKey {
secu := g.api.Securitys[k]
if len(secu.Responses) == 0 {
continue
}
resp := secu.Responses[0]
if resp.Ref != "" {
resp = g.api.Responses[resp.Ref]
}
if resp.Name != req.Name {
continue
}
secus = append(secus, secu)
}
switch len(secus) {
case 0:
g.buf.WriteFormat(`
// Permission verification undefined.
var %s `, vname)
g.Types(req.Type)
g.generateResponseErrorReturn(errName, "401", false)
default:
g.buf.WriteFormat(`
// Permission verification
`)
for _, secu := range secus {
name := g.getSecurityFunctionName(secu)
switch secu.Schema {
case "basic":
g.buf.AddImport("", "strings")
g.buf.WriteFormat(`if strings.HasPrefix(r.Header.Get("Authorization"), "Basic ") { // Call %s.
%s, %s = %s(`, secu.Name, vname, errName, name)
case "bearer":
g.buf.AddImport("", "strings")
g.buf.WriteFormat(`if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { // Call %s.
%s, %s = %s(`, secu.Name, vname, errName, name)
case "apiKey":
req := secu.Requests[0]
if req.Ref != "" {
req = g.api.Requests[req.Ref]
}
switch req.In {
default:
case "header":
g.buf.WriteFormat(`if r.Header.Get("%s") != "" { // Call %s.
%s, %s = %s(`, req.Name, secu.Name, vname, errName, name)
case "query":
g.buf.WriteFormat(`if r.URL.Query().Get("%s") != "" { // Call %s.
%s, %s = %s(`, req.Name, secu.Name, vname, errName, name)
case "cookie":
g.buf.WriteFormat(`if cookie, err := r.Cookie("%s"); err == nil && cookie.Value != "" { // Call %s.
%s, %s = %s(`, req.Name, secu.Name, vname, errName, name)
}
}
if secu.Type != nil {
g.buf.WriteString(`s, `)
}
g.buf.WriteString(`w, r)
} else `)
}
g.buf.AddImport("", "errors")
g.buf.WriteFormat(`{
%s = errors.New("Unauthorized")
}`, errName)
g.generateResponseError(errName, "401", false)
}
default:
g.buf.WriteFormat(`
// Parsing %s.
%s, %s = %s(w, r)`, req.Name, vname, errName, g.getRequestFunctionName(req))
g.buf.WriteFormat(`
if %s != nil {
return
}
`, errName)
}
return nil
}
func (g *GenRoute) generateRequestFunction(req *spec.Request) error {
g.buf.AddImport("", "net/http")
name := g.getRequestFunctionName(req)
if g.only[name] {
return nil
}
g.only[name] = true
g.buf.WriteFormat(`
// %s Parsing the %s for of %s
func %s(w http.ResponseWriter, r *http.Request) (%s `, name, req.In, req.Name, name, g.getVarName(req.Name, req.Type))
g.Types(req.Type)
g.buf.WriteString(`, err error) {
`)
err := g.generateRequestVar(req)
if err != nil {
return err
}
g.buf.WriteString(`
return
}`)
return nil
}
func (g *GenRoute) generateRequestVar(req *spec.Request) error {
name := g.getVarName(req.Name, req.Type)
switch req.In {
case "body":
g.buf.WriteFormat(`
defer r.Body.Close()
`)
switch req.Content {
case "json":
g.buf.AddImport("", "io/ioutil")
g.buf.AddImport("", "encoding/json")
g.buf.WriteFormat(`
var _%s []byte
_%s, err = ioutil.ReadAll(r.Body)`, name, name)
g.generateResponseError("err", "400", false)
g.buf.WriteFormat(`
err = json.Unmarshal(_%s, &%s)`, name, name)
g.generateResponseError("err", "400", false)
case "xml":
g.buf.AddImport("", "io/ioutil")
g.buf.AddImport("", "encoding/xml")
g.buf.WriteFormat(`
var _%s []byte
_%s, err = ioutil.ReadAll(r.Body)`, name, name)
g.generateResponseError("err", "400", false)
g.buf.WriteFormat(`
err = xml.Unmarshal(_%s, &%s)`, name, name)
g.generateResponseError("err", "400", false)
case "formdata":
g.buf.WriteFormat(`
if _%s := r.MultipartForm.File["%s"]; len(_%s) != 0 {
%s, err = _%s[0].Open()`, name, name, name, name, name)
g.generateResponseError("err", "400", false)
g.buf.WriteFormat(`
}
`)
case "file":
g.buf.AddImport("", "io")
g.buf.AddImport("", "bytes")
g.buf.AddImport("", "strings")
g.buf.WriteFormat(`
body := r.Body
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "multipart/form-data") {
if r.MultipartForm == nil {
err = r.ParseMultipartForm(10<<20)
if err != nil {
return
}
}
file := r.MultipartForm.File["%s"]
if len(file) != 0 {
body, err = file[0].Open()
if err != nil {
return
}
}
}
_%s := bytes.NewBuffer(nil)
_, err = io.Copy(_%s, body)`, req.Name, name, name)
g.generateResponseError("err", "400", false)
g.buf.WriteFormat(`
%s = _%s
`, name, name)
case "image":
g.buf.AddImport("", "image")
g.buf.AddImport("_", "image/jpeg")
g.buf.AddImport("_", "image/png")
g.buf.AddImport("", "strings")
g.buf.WriteFormat(`
body := r.Body
defer r.Body.Close()
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "multipart/form-data") {
if r.MultipartForm == nil {
err = r.ParseMultipartForm(10<<20)
if err != nil {
return
}
}
file := r.MultipartForm.File["%s"]
if len(file) != 0 {
body, err = file[0].Open()
if err != nil {
return
}
}
}
%s, _, err = image.Decode(body)`, req.Name, name)
g.generateResponseError("err", "400", false)
}
case "cookie":
g.buf.AddImport("", "net/http")
g.buf.WriteFormat(`
var cookie *http.Cookie
cookie, err = r.Cookie("%s")`, req.Name)
g.generateResponseError("err", "400", false)
g.GenModel.ConvertTo(`cookie.Value`, name, req.Type)
g.generateResponseError("err", "400", false)
case "query":
varName := g.getVarName("raw_"+name, req.Type)
g.buf.WriteFormat(`
var %s = r.URL.Query()["%s"]
`, varName, req.Name)
g.GenModel.ConvertToMulti(varName, name, req.Type, g.explode)
g.generateResponseError("err", "400", false)
case "header":
varName := g.getVarName("raw_"+name, req.Type)
g.buf.WriteFormat(`
var %s = r.Header.Get("%s")
`, varName, req.Name)
g.GenModel.ConvertTo(varName, name, req.Type)
g.generateResponseError("err", "400", false)
case "path":
varName := g.getVarName("raw_"+name, req.Type)
g.buf.WriteFormat(`
var %s = mux.Vars(r)["%s"]
`, varName, req.Name)
g.GenModel.ConvertTo(varName, name, req.Type)
g.generateResponseError("err", "400", false)
default:
return fmt.Errorf("undefine in %s", req.In)
}
return nil
}
| true |
dbeadd3132b0f163b7afed5b1316167cce645fed
|
Go
|
xiupengrong/bsn-sdk-crypto
|
/crypto/eth/ecdsa_test.go
|
UTF-8
| 571 | 2.671875 | 3 |
[] |
no_license
|
[] |
no_license
|
package eth
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"testing"
)
func TestKey(t *testing.T) {
key := "-----BEGIN PRIVATE KEY-----\r\nMIGNAgEAMBAGByqGSM49AgEGBSuBBAAKBHYwdAIBAQQgVxFlqM9/e2SnAOTcBvix\r\nPv+ZG21ku/M5crUavirBLJygBwYFK4EEAAqhRANCAAS6BLPEyNPXvsgE3Z6AC6Qd\r\nb3o3PH9NJHZRlA2m/XFVe0MQ9lY8ZnzpFBVUfQMdi8TZg73I3bCTHGd38++MCLg/\r\n-----END PRIVATE KEY-----"
pk, err := LoadPrivateKey([]byte(key))
if err != nil {
t.Fatal(err)
}
fmt.Println(pk.D.String())
data := "123456"
r, s, v, sig, err := SignData(pk, Hash1([]byte(data)))
if err != nil {
t.Fatal(err)
}
fmt.Println(r.String())
fmt.Println(s.String())
fmt.Println(v.String())
fmt.Println(hex.EncodeToString(sig))
}
func Hash1(msg []byte) []byte {
h := sha256.New()
h.Write([]byte(msg))
hash := h.Sum(nil)
return hash
}
| true |
acf0614dbdf243c23f4c26c1c168597a7d7242d1
|
Go
|
jhanggj/Go_Programming_Practice
|
/src_practice/String_operation/get_one_char_in_string/get_one_char_in_string.go
|
UTF-8
| 684 | 3.609375 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
import "strings"
import "unicode/utf8"
//using strings.Index to find substring
func main() {
//NOTE there are two blanks after comma(,)
tracer := "死神來了, 死神bye bye"
comma := strings.Index(tracer, ",")
fmt.Printf("comma is %d\n", comma)
pos := strings.Index(tracer[comma:], "死神")
fmt.Printf("pos is %d\n", pos)
fmt.Println(comma, pos, tracer[comma+pos:])
fmt.Println(comma, pos, tracer[comma:])
//sol.
//死 神 來 了 , 死 神 b y e b y e
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
fmt.Printf("len of tracer is %d\n", utf8.RuneCountInString(tracer))
}
| true |
7ca1e7694711a72aba9d47ee62e2626aee57b336
|
Go
|
davealexis/seesv
|
/examples/viewer/main.go
|
UTF-8
| 2,697 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/davealexis/seesv"
"github.com/eiannone/keyboard"
"github.com/olekukonko/tablewriter"
)
func main() {
var csvFile seesv.DelimitedFile
DisplayRows := 20
err := csvFile.Open("/path/to/large.csv", 0, true)
if err != nil {
log.Fatal(err)
}
defer csvFile.Close()
fmt.Println()
log.Println(csvFile.RowCount, " rows")
currentRow := int64(0)
displayRows(&csvFile, currentRow, DisplayRows, 0)
if err := keyboard.Open(); err != nil {
panic(err)
}
defer func() {
_ = keyboard.Close()
}()
stop := false
columnShift := 0
columnCount := len(csvFile.Headers) - 1
for stop == false {
fmt.Print(">> ")
char, key, err := keyboard.GetKey()
if err != nil {
panic(err)
}
switch key {
case keyboard.KeyPgup:
if currentRow < int64(DisplayRows) {
currentRow = 0
} else {
currentRow -= int64(DisplayRows)
}
case keyboard.KeyPgdn:
currentRow += int64(DisplayRows)
if currentRow >= csvFile.RowCount {
currentRow = csvFile.RowCount - int64(DisplayRows)
}
case keyboard.KeyArrowRight:
columnShift += 2
if columnShift+15 > columnCount {
columnShift = columnCount - 15
}
case keyboard.KeyArrowLeft:
columnShift -= 2
if columnShift < 0 {
columnShift = 0
}
case keyboard.KeyEsc:
fmt.Print("\033[H\033[2J")
stop = true
case 0:
switch char {
case 'g':
currentRow = 0
case 'G':
currentRow = csvFile.RowCount - int64(DisplayRows)
case '/':
fmt.Print("/")
var input string
fmt.Scan(&input)
input = strings.TrimSuffix(input, "\r\n")
var line int64
line, err := strconv.ParseInt(strings.TrimSuffix(input, "\r\n"), 10, 64)
fmt.Println("Go to:", line)
if err == nil {
currentRow = int64(line)
if currentRow >= csvFile.RowCount {
currentRow = csvFile.RowCount - int64(DisplayRows)
}
}
}
}
if stop == false {
displayRows(&csvFile, currentRow, DisplayRows, columnShift)
}
}
}
func displayRows(csv *seesv.DelimitedFile, start int64, rows int, colShift int) {
rowNum := start
end := start + int64(rows)
colCount := 15
fmt.Print("\033[H\033[2J")
fmt.Println("Press ESC to quit")
fmt.Println(start, "->", end, "of", csv.RowCount)
table := tablewriter.NewWriter(os.Stdout)
table.SetRowSeparator("-")
table.SetRowLine(true)
rowHeaders := append([]string{"Row"}, csv.Headers[colShift:colCount+colShift]...)
table.SetHeader(rowHeaders)
for v := range csv.Rows(start, -1) {
table.Append(append([]string{strconv.FormatInt(rowNum, 10)}, v[colShift:colCount+colShift]...))
rowNum++
if rowNum >= end {
break
}
}
table.Render()
}
| true |
26624122e8637534d2a16a333f84df2af431dec4
|
Go
|
zytell3301/snap-backend
|
/Database/Cassandra/Models/Users.go
|
UTF-8
| 1,809 | 2.734375 | 3 |
[] |
no_license
|
[] |
no_license
|
package Models
import (
"github.com/gocql/gocql"
"golang.org/x/crypto/bcrypt"
"snap/Database/Cassandra"
"time"
)
type Driver struct {
Name string `cql:"name"`
Lastname string `cql:"lastname"`
Vehicle_no string `cql:"vehicle_no"`
Balance int `cql:"Balance"`
Profile_pic string `cql:"profile_pic"`
}
type User struct {
Cassandra.TableMetaData
Id gocql.UUID
Phone string
Password string
Balance int
Driver_details Driver
Created_at time.Time
}
var Users = User{
TableMetaData: Cassandra.TableMetaData{
Table: "users",
Columns: map[string]struct{}{
"id": {},
"phone": {},
"balance": {},
"driver_details": {},
"created_at": {},
},
Pk: map[string]struct{}{"id": {}},
Keyspace: "snap",
},
}
func (u User) GetDriverDetails(conditions map[string]interface{}) (user User, err error) {
statement := u.GetSelectStatement(conditions, []string{"Id", "Driver_details"})
err = statement.Scan(&user.Id, &user.Driver_details)
return
}
func (u User) NewUser(user User) error {
usr := map[string]interface{}{}
password, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
switch err != nil {
case true:
return err
}
batch := Users.Connection.NewBatch(gocql.LoggedBatch)
usr["id"] = user.Id.String()
usr["balance"] = 0
usr["phone"] = user.Phone
usr["password"] = string(password)
usr["driver_details"] = user.Driver_details
usr["created_at"] = time.Now()
Users.NewRecord(usr, batch)
userPkPhone := map[string]interface{}{}
userPkPhone["phone"] = usr["phone"]
userPkPhone["id"] = usr["id"]
userPkPhone["password"] = usr["password"]
UserPkPhone.NewRecord(userPkPhone, batch)
err = u.Connection.ExecuteBatch(batch)
return err
}
| true |
dbba8864cde60064fbf12cd43e3e339deb899888
|
Go
|
AkihiroSuda/cbi
|
/pkg/plugin/base/backend/util/util.go
|
UTF-8
| 2,332 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
/*
Copyright The CBI 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, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"path/filepath"
corev1 "k8s.io/api/core/v1"
)
// InjectConfigMap injects a config map to podSpec and returns the context path
func InjectConfigMap(podSpec *corev1.PodSpec, containerIdx int, configMapRef corev1.LocalObjectReference) string {
const (
// cmVol is a configmap volume (with symlinks)
cmVolName = "cbi-cmcontext-tmp"
cmVolMountPath = "/cbi-cmcontext-tmp"
// vol is an emptyDir volume (without symlinks)
volName = "cbi-cmcontext"
volMountPath = "/cbi-cmcontext"
volContextSubpath = "context"
// initContainer is used for converting cmVol to vol so as to eliminate symlinks
initContainerName = "cbi-cmcontext-init"
initContainerImage = "busybox"
)
contextPath := filepath.Join(volMountPath, volContextSubpath)
cmVol := corev1.Volume{
Name: cmVolName,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: configMapRef,
},
},
}
vol := corev1.Volume{
Name: volName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}
podSpec.Volumes = append(podSpec.Volumes, cmVol, vol)
initContainer := corev1.Container{
Name: initContainerName,
Image: initContainerImage,
Command: []string{"cp", "-rL", cmVolMountPath, contextPath},
VolumeMounts: []corev1.VolumeMount{
{
Name: volName,
MountPath: volMountPath,
},
{
Name: cmVolName,
MountPath: cmVolMountPath,
},
},
}
podSpec.InitContainers = append(podSpec.InitContainers, initContainer)
podSpec.Containers[containerIdx].VolumeMounts = append(podSpec.Containers[containerIdx].VolumeMounts,
corev1.VolumeMount{
Name: volName,
MountPath: volMountPath,
},
)
return contextPath
}
| true |
7c926babbc0700c1c8b58ce535849b3a2e6310f5
|
Go
|
bmwant/jaaam
|
/go/1028_recover_tree_traversal.go
|
UTF-8
| 3,960 | 3.53125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"strconv"
"strings"
)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type deque []*TreeNode
func (d deque) PushBack(v *TreeNode) deque {
return append(d, v)
}
func (d deque) PushFront(v *TreeNode) deque {
// todo: reimplement
return append(d, v)
}
func (d deque) PopBack() (deque, *TreeNode) {
// todo: length check?
l := len(d)
return d[:l-1], d[l-1]
}
func (d deque) PopFront() (deque, *TreeNode) {
// l := len(d)
// todo: length check?
return d[1:], d[0]
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func insert(node *TreeNode, val int, level int, curLevel int) bool {
if curLevel > level {
return false
}
// fmt.Printf("Loking to insert at %d: %d\n", level, curLevel)
// find first vacant slot on this level
if curLevel == level {
if node.Left == nil {
node.Left = &TreeNode{Val: val}
return true
}
if node.Right == nil {
node.Right = &TreeNode{Val: val}
return true
}
}
inserted := false
// traverse tree further, this order is important
if !inserted && node.Right != nil {
inserted = insert(node.Right, val, level, curLevel+1)
}
if !inserted && node.Left != nil {
inserted = insert(node.Left, val, level, curLevel+1)
}
return inserted
}
func runeVal(ch rune) int {
val, _ := strconv.Atoi(fmt.Sprintf("%c", ch))
return val
}
type Pair struct {
Value int
Level int
}
func extractPairs(t string) []Pair {
result := make([]Pair, 0)
isLevel := func(c rune) bool {
return c != '-'
}
isNotLevel := func(c rune) bool {
return c == '-'
}
levels := strings.FieldsFunc(t, isLevel)
values := strings.FieldsFunc(t, isNotLevel)
// insert root
value, _ := strconv.Atoi(values[0])
result = append(result, Pair{Value: value, Level: 0})
for i, l := range levels {
level := len(l)
value, _ = strconv.Atoi(values[i+1])
result = append(result, Pair{Value: value, Level: level})
}
for _, p := range result {
fmt.Println(p.Value, p.Level)
}
return result
}
func recoverFromPreorder(traversal string) *TreeNode {
pairs := extractPairs(traversal)
var root TreeNode = TreeNode{Val: pairs[0].Value}
for _, p := range pairs[1:] {
insert(&root, p.Value, p.Level, 1)
}
return &root
}
func treeToList(t *TreeNode) (res []int) {
dq := make(deque, 0)
dq = dq.PushBack(t)
var current *TreeNode
for len(dq) > 0 {
dq, current = dq.PopFront()
// fmt.Println(current.Val)
if current.Left != nil {
dq = dq.PushBack(current.Left)
}
if current.Right != nil {
dq = dq.PushBack(current.Right)
}
res = append(res, current.Val)
}
return res
}
func treeToPrint(t *TreeNode) (res []*TreeNode) {
dq := make(deque, 0)
dq = dq.PushBack(t)
var current *TreeNode
for len(dq) > 0 {
dq, current = dq.PopFront()
fmt.Println(current)
res = append(res, current)
if current == nil {
continue
}
if current.Left == nil && current.Right == nil {
continue
}
if current.Left != nil {
dq = dq.PushBack(current.Left)
} else {
dq = dq.PushBack(nil)
}
if current.Right != nil {
dq = dq.PushBack(current.Right)
} else {
dq = dq.PushBack(nil)
}
}
for _, t := range res {
if t == nil {
fmt.Print("null ")
} else {
fmt.Printf("%d ", t.Val)
}
}
fmt.Println("")
return res
}
func main() {
var t1, t2, t3 TreeNode
t1.Val = 0
t2.Val = 1
t3.Val = 2
t1.Left = &t2
t2.Left = &t3
// root := &t1
// fmt.Println(treeToList(root))
// head := recoverFromPreorder("1-2--3--4-5--6--7")
// fmt.Println(treeToList(head)) // [1,2,5,3,4,6,7]
// head = recoverFromPreorder("1-2--3---4-5--6---7")
// fmt.Println(treeToList(head)) // [1,2,5,3,null,6,null,4,null,7]
// head = recoverFromPreorder("1-401--349---90--88")
// fmt.Println(treeToList(head)) // [1,401,null,349,88,90]
head := recoverFromPreorder("1-2--3---4-5--6---7")
treeToPrint(head) // [1,2,5,3,null,6,null,4,null,7]
}
| true |
2a1e1fd0ff83a2dbcfe83c8ccd42e8cf9c2163ab
|
Go
|
dolzenko/cron
|
/cron.go
|
UTF-8
| 1,190 | 3.453125 | 3 |
[] |
no_license
|
[] |
no_license
|
package cron
import (
"sync"
"time"
)
type cbF func() error
type errCbF func(error)
type task struct {
dur time.Duration
cb cbF
}
type cron struct {
tasks chan task
errCb errCbF
sync.Mutex
}
// NewCron returns ready to use (and running) scheduler
func NewCron() *cron {
c := &cron{
tasks: make(chan task),
}
go c.loop()
return c
}
var defaultCron = NewCron()
// Every schedules execution of callback(s)
func Every(dur time.Duration, cbs ...cbF) *cron {
return defaultCron.Every(dur, cbs...)
}
// OnError registers task error handler
func OnError(cb errCbF) *cron {
return defaultCron.OnError(cb)
}
// Every schedules execution of callback(s)
func (c *cron) Every(dur time.Duration, cbs ...cbF) *cron {
for _, cb := range cbs {
c.tasks <- task{dur, cb}
}
return c
}
// OnError registers task error handler
func (c *cron) OnError(cb errCbF) *cron {
c.errCb = cb
return c
}
func (c *cron) loop() {
for t := range c.tasks {
go c.taskLoop(t)
}
}
func (c *cron) taskLoop(t task) {
t.run(c.errCb)
for range time.NewTicker(t.dur).C {
t.run(c.errCb)
}
}
func (t task) run(errCb errCbF) {
err := t.cb()
if err != nil && errCb != nil {
errCb(err)
}
}
| true |
fe53b1434f89c334ae9dd01db336bd7dd755200d
|
Go
|
sxlongwork/gowork
|
/src/go_code/chapter06/stringdemo/main.go
|
UTF-8
| 2,173 | 3.296875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"go_code/chapter06/stringdemo/arraylist"
"go_code/chapter06/stringdemo/stack"
"go_code/chapter06/stringdemo/btree"
"bufio"
"os"
"strings"
"strconv"
"sort"
)
type A struct{
name string
}
/*
去除数组重复元素
输入:1 1 1 1 3 4 5 3
输出:1 3 4 5
*/
func test() {
reader := bufio.NewReader(os.Stdin)
data, _, _ := reader.ReadLine()
datalist := strings.Fields(string(data))
var numlist []int = make([]int, 0,10)
for _, v := range datalist {
num, _ := strconv.Atoi(v)
numlist = append(numlist, num)
}
sort.Sort(sort.IntSlice(numlist))
for i := 0; i< len(numlist)-1; i++ {
if numlist[i] ^ numlist[i+1] == 0 {
numlist = append(numlist[:i], numlist[i+1:]...)
i--
}
}
for _, v := range numlist{
fmt.Print(v, " ")
}
}
func main1() {
var list arraylist.List = new(arraylist.ArrayList)
list.Append("aa")
list.Append("bb")
list.Append(12)
list.Delete(1)
// list.Clear()
for i:=0; i<20 ;i++{
list.Insert(1, "x3")
}
fmt.Println(list)
str := make([]int, 10, 10)
str[0] = 1
str[1] = 3
str = append(str, 10)
fmt.Println(str)
fmt.Println("--------------------------------------------")
mystack := stack.NewStack()
// mystack.Push(1)
// mystack.Push(2)
for i :=0; i<50;i++ {
mystack.Push(i)
}
fmt.Println(mystack)
fmt.Println(mystack.Size())
fmt.Println(mystack.Pop())
fmt.Println(mystack.Pop())
fmt.Println(mystack.Pop())
fmt.Println(mystack)
fmt.Println(mystack.Size())
fmt.Println("--------------------------------------------")
var m map[string]string = make(map[string]string, 1)
m["aa"] = "aa"
fmt.Printf("%p\n",m)
var a A = A{name:"oh"}
fmt.Printf("%v",a)
fmt.Println("--------------------------------------------")
}
func main(){
var root = btree.CreateBtree(5)
root.Lchild = btree.CreateBtree(4)
root.Rchild = btree.CreateBtree(6)
root.Lchild.Lchild = btree.CreateBtree(3)
root.Lchild.Rchild = btree.CreateBtree(4)
node := root.FindNode(root, 4)
if node != nil {
fmt.Println(node.Data)
}
fmt.Println(root.GetHeight(root))
reader := bufio.NewReader(os.Stdin)
data,_,_ := reader.ReadLine()
fmt.Printf("%T\n",data)
fmt.Println(len(data))
}
| true |
deff318635433af689f8b9ec7c74abf248f4508a
|
Go
|
phil-mansfield/rogue
|
/item/list_buffer.go
|
UTF-8
| 11,394 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package item
import (
"fmt"
"math"
"github.com/phil-mansfield/rogue/error"
)
// BufferIndex is an integer type used to index into ListBuffer.
//
// Since BufferIndex may be changed to different size or to a type of unknown
// signage, all BufferIndex literals must be constructed from 0, 1,
// MaxBufferCount, and NilIndex alone.
type BufferIndex int16
// Note that the usage of "Count" and "Length" in constant names *is* actually
// consistent.
const (
// MaxBufferCount is the largest possible value of ListBuffer.Count.
MaxBufferCount = math.MaxInt16
// NilIndex is a sentinel ListBuffer index value. It is analogous to a a
// nil pointer.
NilIndex = -1
// defaultBufferLength is the length of an empty ListBuffer.
defaultBufferLength = 1 << 8
)
// Node is a wrapper around the type Item which allows it to be an element
// in a linked list.
//
// Next and Prev reference the indices of other Items within the same instance
// of ListBuffer.
type Node struct {
Item Item
Next, Prev BufferIndex
}
// ListBuffer is a data structure which represents numerous lists of items.
type ListBuffer struct {
FreeHead BufferIndex
Buffer []Node
Count BufferIndex
}
// New creates a new ListBuffer instance.
func New() *ListBuffer {
buf := new(ListBuffer)
buf.Init()
return buf
}
// Init initializes a blank ListBuffer instance.
func (buf *ListBuffer) Init() {
buf.Buffer = make([]Node, defaultBufferLength)
buf.FreeHead = 0
buf.Count = 0
for i := 0; i < len(buf.Buffer); i++ {
buf.Buffer[i].Item.Clear()
buf.Buffer[i].Prev = BufferIndex(i - 1)
buf.Buffer[i].Next = BufferIndex(i + 1)
}
buf.Buffer[0].Prev = NilIndex
buf.Buffer[len(buf.Buffer)-1].Next = NilIndex
}
// Singleton creates a singleton list containing only the given item.
//
// Singleton returns an error if it is passed
// an uninitialized item, or if the buf is full.
//
// It is correct to call buf.IsFull() prior to all calls to
// buf.Singleton(), since it is not possible to switch upon the type of error
// to identify whether the error has a recoverable cause.
func (buf *ListBuffer) Singleton(item Item) (BufferIndex, *error.Error) {
if buf.IsFull() {
desc := fmt.Sprintf(
"buf has reached maximum capacity of %d Items.",
MaxBufferCount,
)
return NilIndex, error.New(error.Value, desc)
} else if item.Type == Uninitialized {
return NilIndex, error.New(error.Value, "item is uninitialized.")
}
return buf.internalSingleton(item), nil
}
func (buf *ListBuffer) internalSingleton(item Item) BufferIndex {
if buf.Count == BufferIndex(len(buf.Buffer)) {
buf.Buffer = append(buf.Buffer, Node{item, NilIndex, NilIndex})
buf.Count++
return BufferIndex(len(buf.Buffer) - 1)
}
idx := buf.FreeHead
buf.Buffer[idx].Item = item
buf.FreeHead = buf.Buffer[idx].Next
buf.internalUnlink(idx)
buf.Count++
return idx
}
// Link connects the items at indices prev and next so that the item at prev
// comes before the item at next.
//
// Link returns an error if prev or next are not valid indices into buf or if
// the linking would break a pre-existing list or if one of the indices accesses
// a .
func (buf *ListBuffer) Link(prev, next BufferIndex) *error.Error {
// If your functions don't have 50 lines of error handling for two lines
// of state altering-code, you aren't cautious enough.
inRange, initialized := buf.legalIndex(prev)
if !inRange {
desc := fmt.Sprintf(
"prev, %d, is out of range for IndexBuffer of length %d.",
prev, len(buf.Buffer),
)
return error.New(error.Value, desc)
} else if !initialized {
desc := fmt.Sprintf(
"Item at prev, %d, has the Type value Uninitialized.", prev,
)
return error.New(error.Value, desc)
}
inRange, initialized = buf.legalIndex(next)
if !inRange {
desc := fmt.Sprintf(
"next, %d, is out of range for IndexBuffer of length %d.",
next, len(buf.Buffer),
)
return error.New(error.Value, desc)
} else if !initialized {
desc := fmt.Sprintf(
"Item at next, %d, has the Type value Uninitialized.", next,
)
return error.New(error.Value, desc)
}
if buf.Buffer[prev].Next != NilIndex {
desc := fmt.Sprintf(
"ItemNode at prev, %d, is already linked to Next ItemNode at %d.",
prev, buf.Buffer[prev].Next,
)
return error.New(error.Value, desc)
}
if buf.Buffer[next].Prev != NilIndex {
desc := fmt.Sprintf(
"ItemNode at next, %d, is already linked to Prev ItemNode at %d.",
next, buf.Buffer[next].Prev,
)
return error.New(error.Value, desc)
}
buf.internalLink(prev, next)
return nil
}
func (buf *ListBuffer) internalLink(prev, next BufferIndex) {
buf.Buffer[next].Prev = prev
buf.Buffer[prev].Next = next
}
// Unlink removes the item at the given index from its current list.
//
// An error is returned if idx is not a valid index into the buffer or if
// it represents an uninitialized item.
func (buf *ListBuffer) Unlink(idx BufferIndex) *error.Error {
inRange, initialized := buf.legalIndex(idx)
if !inRange {
desc := fmt.Sprintf(
"idx, %d, is out of range for IndexBuffer of length %d.",
idx, len(buf.Buffer),
)
return error.New(error.Value, desc)
} else if !initialized {
desc := fmt.Sprintf(
"Item at idx, %d, has the Type value Uninitialized.", idx,
)
return error.New(error.Value, desc)
}
buf.internalUnlink(idx)
return nil
}
func (buf *ListBuffer) internalUnlink(idx BufferIndex) {
next := buf.Buffer[idx].Next
prev := buf.Buffer[idx].Prev
if prev != NilIndex {
buf.Buffer[prev].Next = next
}
if next != NilIndex {
buf.Buffer[next].Prev = prev
}
buf.Buffer[idx].Next = NilIndex
buf.Buffer[idx].Prev = NilIndex
}
// Delete frees the buffer resources associated with the item at the given
// index.
//
// An error is returned if idx is not a valid index into buffer or if it
// represents an uninitialized item.
func (buf *ListBuffer) Delete(idx BufferIndex) *error.Error {
inRange, initialized := buf.legalIndex(idx)
if !inRange {
desc := fmt.Sprintf(
"idx, %d, is out of range for IndexBuffer of length %d.",
idx, len(buf.Buffer),
)
return error.New(error.Value, desc)
} else if !initialized {
desc := fmt.Sprintf(
"Item at idx, %d, has the Type value Uninitialized.", idx,
)
return error.New(error.Value, desc)
}
buf.internalDelete(idx)
return nil
}
func (buf *ListBuffer) internalDelete(idx BufferIndex) {
buf.internalUnlink(idx)
if buf.FreeHead != NilIndex {
buf.internalLink(idx, buf.FreeHead)
}
node := &buf.Buffer[idx]
node.Item.Clear()
node.Next = buf.FreeHead
node.Prev = NilIndex
buf.FreeHead = idx
buf.Count--
}
// IsFull returns true if no more items can be added to the buffer.
func (buf *ListBuffer) IsFull() bool {
return buf.Count >= MaxBufferCount
}
// Get returns the item stored at the given index within the buffer.
//
// An error is returned if idx is not a valid index into the buffer or if it
// represents an uninitialized item.
func (buf *ListBuffer) Get(idx BufferIndex) (Item, *error.Error) {
inRange, initialized := buf.legalIndex(idx)
if !inRange {
desc := fmt.Sprintf(
"idx, %d, is out of range for IndexBuffer of length %d.",
idx, len(buf.Buffer),
)
return Item{}, error.New(error.Value, desc)
} else if !initialized {
desc := fmt.Sprintf(
"Item at idx, %d, has the Type value Uninitialized.", idx,
)
return Item{}, error.New(error.Value, desc)
}
return buf.Buffer[idx].Item, nil
}
// Set updates the item stored at the given index within the buffer.
//
// An error is returned if idx is not a valid index into the buffer or if it
// represents an uninitialized item.
func (buf *ListBuffer) Set(idx BufferIndex, item Item) (*error.Error) {
inRange, initialized := buf.legalIndex(idx)
if !inRange {
desc := fmt.Sprintf(
"idx, %d, is out of range for IndexBuffer of length %d.",
idx, len(buf.Buffer),
)
return error.New(error.Value, desc)
} else if !initialized {
desc := fmt.Sprintf(
"Item at idx, %d, has the Type value Uninitialized.", idx,
)
return error.New(error.Value, desc)
}
buf.Buffer[idx].Item = item
return nil
}
// legalIndex determines the legality of accessing the buffer at idx. inRange
// is true if the index is valid and initialized is true if there is an valid
// item at idx.
func (buf *ListBuffer) legalIndex(idx BufferIndex) (inRange, initialized bool) {
inRange = idx >= 0 && idx < BufferIndex(len(buf.Buffer))
if inRange {
initialized = buf.Buffer[idx].Item.Type != Uninitialized
} else {
initialized = true
}
return inRange, initialized
}
// Check performs various consistency checks on the buffer and returns an error
// indicating which the first failed check. If all checks pass, nil is returned.
func (buf *ListBuffer) Check() *error.Error {
// Check that the buffer isn't too long.
if len(buf.Buffer) > MaxBufferCount {
desc := fmt.Sprintf(
"Buffer length of %d is larger than max of %d.",
len(buf.Buffer), MaxBufferCount,
)
return error.New(error.Sanity, desc)
}
// Check that all items are valid.
for i := 0; i < len(buf.Buffer); i++ {
if err := buf.Buffer[i].Item.Check(); err != nil { return err }
}
// Check that the item count is correct.
count := 0
for i := 0; i < len(buf.Buffer); i++ {
if buf.Buffer[i].Item.Type != Uninitialized {
count++
}
}
if BufferIndex(count) != buf.Count {
desc := fmt.Sprintf(
"buf.Count = %d, but there are %d items in buffer.",
buf.Count, count,
)
return error.New(error.Sanity, desc)
}
// Check all Prev indices.
for i := 0; i < len(buf.Buffer); i++ {
prev := buf.Buffer[i].Prev
if prev != NilIndex && buf.Buffer[prev].Next != BufferIndex(i) {
desc := fmt.Sprintf(
"Prev index of item %d is %d, but Next index of item %d is %d.",
i, prev, prev, buf.Buffer[prev].Next,
)
return error.New(error.Sanity, desc)
}
}
// Check all Next indices.
for i := 0; i < len(buf.Buffer); i++ {
next := buf.Buffer[i].Next
if next != NilIndex && buf.Buffer[next].Prev != BufferIndex(i) {
desc := fmt.Sprintf(
"Next index of item %d is %d, but Prev index of item %d is %d.",
i, next, next, buf.Buffer[next].Prev,
)
return error.New(error.Sanity, desc)
}
}
// Check for cycles.
checkBuffer := make([]bool, len(buf.Buffer))
for i := 0; i < len(buf.Buffer); i++ {
if !checkBuffer[i] && buf.hasCycle(BufferIndex(i), checkBuffer) {
desc := fmt.Sprintf("List with head at index %d contains cycle.", i)
return error.New(error.Sanity, desc)
}
}
return nil
}
// hasCycle returns true if there is a cycle after in the list following the
// given index and that cycle has not already been detected.
func (buf *ListBuffer) hasCycle(idx BufferIndex, checkBuffer []bool) bool {
checkBuffer[idx] = true
tortise := idx
hare := idx
for hare != NilIndex {
hare = buf.Incr(buf.Incr(hare))
tortise = buf.Incr(tortise)
if hare != NilIndex { checkBuffer[hare] = true }
if tortise != NilIndex { checkBuffer[tortise] = true }
if hare == tortise && hare != NilIndex {
return true
}
}
return false
}
// Incr returns the index of item which follows idx in the current list.
func (buf *ListBuffer) Incr(idx BufferIndex) BufferIndex {
if idx == NilIndex {
return NilIndex
}
return buf.Buffer[idx].Next
}
func (buf *ListBuffer) Decr(idx BufferIndex) BufferIndex {
if idx == NilIndex {
return NilIndex
}
return buf.Buffer[idx].Prev
}
| true |
282c5c8a6226848eb68b4ceb144292755ca91820
|
Go
|
liblxn/lxnc
|
/internal/cldr/numbering_system.go
|
UTF-8
| 1,091 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package cldr
import (
"encoding/xml"
"unicode/utf8"
)
// NumberingSystems holds all numbering systems that could be found.
// The key specifies the system id, e.g. "latn".
type NumberingSystems map[string]NumberingSystem // system id => numbering system
func (n *NumberingSystems) decode(d *xmlDecoder, _ xml.StartElement) {
*n = make(map[string]NumberingSystem)
d.DecodeElem("numberingSystem", func(d *xmlDecoder, elem xml.StartElement) {
if xmlAttrib(elem, "type") == "numeric" {
var sys NumberingSystem
if err := sys.decode(elem); err != nil {
d.ReportErr(err, elem)
return
}
(*n)[sys.ID] = sys
}
d.SkipElem()
})
}
// NumberingSystem holds the relevant data for a single numbering system.
type NumberingSystem struct {
ID string
Digits []rune
}
func (s *NumberingSystem) decode(elem xml.StartElement) error {
s.ID = xmlAttrib(elem, "id")
s.Digits = make([]rune, 0, 10)
digits := xmlAttrib(elem, "digits")
for digits != "" {
ch, n := utf8.DecodeRuneInString(digits)
s.Digits = append(s.Digits, ch)
digits = digits[n:]
}
return nil
}
| true |
c308f9a0569f3a15dab6e4702a993dcbd736311d
|
Go
|
Herocod3r/fast-r
|
/pkg/watcher/queue.go
|
UTF-8
| 1,084 | 3.65625 | 4 |
[] |
no_license
|
[] |
no_license
|
package watcher
import (
"sync"
)
// ItemQueue the queue of Items
type PacketDurationQueue struct {
items []float32
lock sync.RWMutex
}
// New creates a new ItemQueue
func NewItemQueue() *PacketDurationQueue {
return &PacketDurationQueue{items: make([]float32, MinimumSpeedBlock)}
}
// Enqueue adds an Item to the end of the queue
func (s *PacketDurationQueue) Enqueue(t float32) {
s.lock.Lock()
s.items = append(s.items, t)
s.lock.Unlock()
}
// Dequeue removes an Item from the start of the queue
func (s *PacketDurationQueue) Dequeue() float32 {
s.lock.Lock()
item := s.items[0]
s.items = s.items[1:len(s.items)]
s.lock.Unlock()
return item
}
// Front returns the item next in the queue, without removing it
func (s *PacketDurationQueue) Front() float32 {
s.lock.RLock()
item := s.items[0]
s.lock.RUnlock()
return item
}
// IsEmpty returns true if the queue is empty
func (s *PacketDurationQueue) IsEmpty() bool {
return len(s.items) == 0
}
// Size returns the number of Items in the queue
func (s *PacketDurationQueue) Size() int {
return len(s.items)
}
| true |
579bdb194211a290d083da9d74bd430a872dbae3
|
Go
|
m3db/m3
|
/src/aggregator/aggregation/quantile/cm/list_test.go
|
UTF-8
| 2,690 | 2.78125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) 2016 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, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cm
import (
"testing"
"github.com/stretchr/testify/require"
)
func validateList(t *testing.T, l *sampleList, expected []float64) {
t.Helper()
require.Equal(t, l.Len(), len(expected))
i := 0
for sample := l.Front(); sample != nil; sample = sample.next {
require.Equal(t, expected[i], sample.value)
i++
}
if len(expected) == 0 {
require.Nil(t, l.head)
require.Nil(t, l.tail)
} else {
require.Equal(t, l.Front(), l.head)
require.Nil(t, l.head.prev)
require.Equal(t, l.Back(), l.tail)
require.Nil(t, l.tail.next)
}
}
func TestSampleListPushBack(t *testing.T) {
var (
l sampleList
iter = 10
inputs = make([]float64, iter)
)
for i := 0; i < iter; i++ {
inputs[i] = float64(i)
s := l.Acquire()
s.value = float64(i)
l.PushBack(s)
}
validateList(t, &l, inputs)
}
func TestSampleListInsertBefore(t *testing.T) {
var (
l sampleList
iter = 10
inputs = make([]float64, iter)
)
var prev *Sample
for i := iter - 1; i >= 0; i-- {
inputs[i] = float64(i)
sample := l.Acquire()
sample.value = float64(i)
if i == iter-1 {
l.PushBack(sample)
} else {
l.InsertBefore(sample, prev)
}
prev = sample
}
validateList(t, &l, inputs)
}
func TestSampleListRemove(t *testing.T) {
var (
l sampleList
iter = 10
inputs = make([]float64, iter)
)
for i := 0; i < iter; i++ {
inputs[i] = float64(i)
sample := l.Acquire()
sample.value = float64(i)
l.PushBack(sample)
}
for i := 0; i < iter; i++ {
elem := l.Front()
l.Remove(elem)
validateList(t, &l, inputs[i+1:])
}
}
| true |
aa70109925e8efb283753736baf48ff373f8dcb5
|
Go
|
mrajo/hackerrank-go
|
/challenges/algorithms/warmup/angry-children/main.go
|
UTF-8
| 757 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
"sort"
)
func spanDistance(a []int) int {
return a[len(a) - 1] - a[0]
}
func minimumSpanningSlice(a []int, slice_len int) []int {
sort.Ints(a)
min_slice := a[:slice_len]
span_val := spanDistance(min_slice)
for i := 1; i < len(a) - slice_len - 1; i++ {
tmp_span := a[i:i + slice_len]
tmp_val := spanDistance(tmp_span)
if tmp_val < span_val {
min_slice = tmp_span
span_val = tmp_val
}
}
return min_slice
}
func main() {
var n, kids, size int
var sizes []int
fmt.Scanf("%v %v", &n, &kids)
for i := 0; i < n; i++ {
fmt.Scan(&size)
sizes = append(sizes, size)
}
min_span_slice := minimumSpanningSlice(sizes, kids)
fmt.Println(min_span_slice[len(min_span_slice) - 1] - min_span_slice[0])
}
| true |
802232742ce896872b98b68b288d01c016881329
|
Go
|
tisnik/go-root
|
/article_A8/03_bigint_large_numbers.go
|
UTF-8
| 196 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"fmt"
"math/big"
)
func main() {
var x big.Int
x.SetInt64(2)
var z big.Int
z.SetInt64(1)
for i := 0; i < 100; i++ {
z.Mul(&z, &x)
fmt.Println(z.Text(10))
}
}
| true |
0aa0eba2a60062e975b1476129574e587027db09
|
Go
|
git4example/port-checker
|
/pkg/logging/json.go
|
UTF-8
| 1,860 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package logging
import (
"encoding/json"
"fmt"
"os"
"time"
)
type jsonLogger struct {
level Level
nodeID int
}
func createJSONLogger(level Level, nodeID int) jsonLogger {
return jsonLogger{
level: level,
nodeID: nodeID,
}
}
func makeJSON(level Level, nodeID int, message string, fargs ...interface{}) string {
type jsonPayload struct {
Level string `json:"level"`
Message string `json:"message"`
Time time.Time `json:"time"` // generated on the fly
NodeID int `json:"node"` // constant on the instance
}
payload := jsonPayload{
Level: level.string(),
Message: fmt.Sprintf(message, fargs...),
Time: time.Now(),
NodeID: nodeID,
}
b, err := json.Marshal(payload)
if err != nil {
b, _ := json.Marshal(&jsonPayload{
Level: LEVELERROR.string(),
Message: fmt.Sprintf("cannot make JSON (%s) for payload: %v", err, payload),
Time: time.Now(),
NodeID: nodeID,
})
return string(b)
}
return string(b)
}
func (logger *jsonLogger) fatal(message string, fargs ...interface{}) {
fmt.Println(makeJSON(LEVELFATAL, logger.nodeID, message, fargs...))
os.Exit(1)
}
func (logger *jsonLogger) error(message string, fargs ...interface{}) {
if logger.level >= LEVELERROR {
fmt.Println(makeJSON(LEVELERROR, logger.nodeID, message, fargs...))
}
}
func (logger *jsonLogger) warn(message string, fargs ...interface{}) {
if logger.level >= LEVELWARNING {
fmt.Println(makeJSON(LEVELWARNING, logger.nodeID, message, fargs...))
}
}
func (logger *jsonLogger) success(message string, fargs ...interface{}) {
if logger.level >= LEVELSUCCESS {
fmt.Println(makeJSON(LEVELSUCCESS, logger.nodeID, message, fargs...))
}
}
func (logger *jsonLogger) info(message string, fargs ...interface{}) {
if logger.level >= LEVELINFO {
fmt.Println(makeJSON(LEVELINFO, logger.nodeID, message, fargs...))
}
}
| true |
235c1d610fa3d9285de4119d746c2e73b0b483bb
|
Go
|
g4s8/local-cdn
|
/local-cdn.go
|
UTF-8
| 4,392 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"bytes"
"flag"
"fmt"
"github.com/bclicn/color"
"github.com/elazarl/goproxy"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
)
const (
flagHeader = "X-LocalCDN"
)
var (
cache = make(map[string]*entry)
tmpDir string
dryRun, verbose bool
host string
port int
)
type entry struct {
File string
Source *http.Response
Hits int
}
func main() {
var pid string
flag.StringVar(&host, "host", "", "host to cache")
flag.IntVar(&port, "port", 8010, "proxy port")
flag.BoolVar(&dryRun, "dry", false, "skip cache")
flag.BoolVar(&verbose, "verbose", false, "print cached responses and hits")
flag.StringVar(&pid, "pid", "", "pidfile path")
flag.Parse()
if host == "" {
flag.Usage()
panic("host required")
}
if pid == "" {
writePidFile(pid)
}
tmp, err := ioutil.TempDir("/tmp", "local-cdn")
if err != nil {
panic(err)
}
tmpDir = tmp
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
defer os.Exit(0)
cleanup()
if pid != "" {
os.Remove(pid)
}
}()
fmt.Printf("starting on port %d to cache requests to %s\n", port, host)
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest(goproxy.DstHostIs(host)).Do(goproxy.FuncReqHandler(onRequest))
proxy.OnResponse(goproxy.DstHostIs(host)).Do(goproxy.FuncRespHandler(onResponse))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), proxy))
}
func cleanup() {
fmt.Print("cleaning up...")
if err := os.RemoveAll(tmpDir); err != nil {
panic(err)
}
fmt.Printf("\t[done]\n")
}
func onRequest(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
name := cacheName(r)
entry := cache[name]
if entry != nil {
entry.Hits++
if verbose {
fmt.Println(color.Green(fmt.Sprintf("HIT %d: %s", entry.Hits, name)))
}
r.Header.Set(flagHeader, "1")
return r, entry.response(r)
}
return r, nil
}
func onResponse(rsp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if rsp.StatusCode == 200 && ctx.Req.Method == "GET" {
if ctx.Req.Header.Get(flagHeader) == "1" {
return rsp
}
tmp, err := ioutil.TempFile(tmpDir, "rsp_")
if err != nil {
panic(err)
}
defer tmp.Close()
if _, err := io.Copy(tmp, rsp.Body); err != nil {
panic(err)
}
name := cacheName(ctx.Req)
if verbose {
fmt.Println(color.Yellow(fmt.Sprintf("CACHE: %s", name)))
}
entry := &entry{
File: tmp.Name(),
Source: rsp,
Hits: 0,
}
if !dryRun {
cache[name] = entry
}
return copyResponse(rsp, ctx.Req, tmp.Name())
}
return rsp
}
func cacheName(req *http.Request) string {
return fmt.Sprintf("[%s][%s][%s]", req.Method, req.URL.Host, req.URL.Path)
}
func (entry *entry) response(req *http.Request) *http.Response {
return copyResponse(entry.Source, req, entry.File)
}
func copyResponse(proto *http.Response, req *http.Request, body string) *http.Response {
file, err := os.Open(body)
if err != nil {
panic(err)
}
defer file.Close()
var buf bytes.Buffer
len, err := io.Copy(&buf, file)
if err != nil {
panic(err)
}
resp := &http.Response{
Status: proto.Status,
StatusCode: proto.StatusCode,
Proto: proto.Proto,
ProtoMajor: proto.ProtoMajor,
ProtoMinor: proto.ProtoMinor,
Request: req,
Header: proto.Header,
Body: ioutil.NopCloser(&buf),
ContentLength: len,
}
return resp
}
// Got it from https://gist.github.com/davidnewhall/3627895a9fc8fa0affbd747183abca39
// Write a pid file, but first make sure it doesn't exist with a running pid.
func writePidFile(pidFile string) error {
// Read in the pid file as a slice of bytes.
if piddata, err := ioutil.ReadFile(pidFile); err == nil {
// Convert the file contents to an integer.
if pid, err := strconv.Atoi(string(piddata)); err == nil {
// Look for the pid in the process list.
if process, err := os.FindProcess(pid); err == nil {
// Send the process a signal zero kill.
if err := process.Signal(syscall.Signal(0)); err == nil {
// We only get an error if the pid isn't running, or it's not ours.
return fmt.Errorf("pid already running: %d", pid)
}
}
}
}
// If we get here, then the pidfile didn't exist,
// or the pid in it doesn't belong to the user running this app.
return ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d", os.Getpid())), 0664)
}
| true |
49b8b8712090a60a715ee0bcfb6979b6d3d91cda
|
Go
|
forkkit/gorithms
|
/sorting/insertion_sort.go
|
UTF-8
| 522 | 3.609375 | 4 |
[] |
no_license
|
[] |
no_license
|
package sorting
// InsertionSortInt sorts the items in a list using
// InsertionSort algorithm
func InsertionSortInt(list []int) {
var sorted []int
for _, item := range list {
sorted = insert(sorted, item)
}
for i, val := range sorted {
list[i] = val
}
}
func insert(sortedList []int, item int) []int {
for i := 0; i < len(sortedList); i++ {
if item < sortedList[i] {
return append(sortedList[:i], append([]int{item}, sortedList[i:]...)...)
}
}
return append(sortedList, item)
}
// func BinarySearch
| true |
004e214a7fa143687acfd47b5ba0ae4d34df8aac
|
Go
|
justinfargnoli/lshforest
|
/pkg/lshtree/lshtree.go
|
UTF-8
| 532 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package lshtree
import "github.com/justinfargnoli/lshforest/pkg/hash"
// Element is an element in the trie
type Element struct {
hash *[]hash.Bit
Vector *[]float64
Value interface{}
}
// NewElement constructs an element stored in the node of a LSHTree
func NewElement(hash *[]hash.Bit, vector *[]float64, value interface{}) Element {
return Element{hash: hash, Vector: vector, Value: value}
}
// LSHTree is a trie within the LSHForest
type LSHTree interface {
Insert(Element) error
Descend(*[]hash.Bit) (*Node, uint)
}
| true |
c20a09785cd7e6ebed6201e1281159f839fdda32
|
Go
|
TomatoCode/openedge
|
/module/logger/logger.go
|
UTF-8
| 6,337 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package logger
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/baidu/openedge/module/config"
"github.com/sirupsen/logrus"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
// Entry logging entry
type Entry struct {
entry *logrus.Entry
}
// WithFields adds a map of fields to the Entry.
func (e *Entry) WithFields(vs ...string) *Entry {
fs := logrus.Fields{}
for index := 0; index < len(vs)-1; index = index + 2 {
fs[vs[index]] = vs[index+1]
}
return &Entry{entry: e.entry.WithFields(fs)}
}
// WithError adds an error as single field (using the key defined in ErrorKey) to the Entry.
func (e *Entry) WithError(err error) *Entry {
return &Entry{entry: e.entry.WithError(err)}
}
// // Debug log debug info
// func (e *Entry) Debug(args ...interface{}) {
// e.entry.Debug(args...)
// }
// // Info log info
// func (e *Entry) Info(args ...interface{}) {
// e.entry.Info(args...)
// }
// // Warn log warning info
// func (e *Entry) Warn(args ...interface{}) {
// e.entry.Warn(args...)
// }
// // Error log error info
// func (e *Entry) Error(args ...interface{}) {
// e.entry.Error(args...)
// }
// Debugf log debug info
func (e *Entry) Debugf(format string, args ...interface{}) {
e.entry.Debugf(format, args...)
}
// Infof log info
func (e *Entry) Infof(format string, args ...interface{}) {
e.entry.Infof(format, args...)
}
// Warnf log warning info
func (e *Entry) Warnf(format string, args ...interface{}) {
e.entry.Warnf(format, args...)
}
// Errorf log error info
func (e *Entry) Errorf(format string, args ...interface{}) {
e.entry.Errorf(format, args...)
}
// Debugln log debug info
func (e *Entry) Debugln(args ...interface{}) {
e.entry.Debugln(args...)
}
// Infoln log info
func (e *Entry) Infoln(args ...interface{}) {
e.entry.Infoln(args...)
}
// Warnln log warning info
func (e *Entry) Warnln(args ...interface{}) {
e.entry.Warnln(args...)
}
// Errorln log error info
func (e *Entry) Errorln(args ...interface{}) {
e.entry.Errorln(args...)
}
var root = &Entry{entry: logrus.NewEntry(logrus.New())}
// Init init logger
func Init(c config.Logger, fields ...string) error {
var logOutWriter io.Writer
if c.Console == true {
logOutWriter = os.Stdout
} else {
logOutWriter = ioutil.Discard
}
logLevel, err := logrus.ParseLevel(c.Level)
if err != nil {
logLevel = logrus.DebugLevel
}
var fileHook logrus.Hook
if len(c.Path) != 0 {
err := os.MkdirAll(filepath.Dir(c.Path), 0755)
if err != nil {
return err
}
fileHook, err = newFileHook(fileConfig{
Filename: c.Path,
Formatter: newFormatter(c.Format, false),
Level: logLevel,
MaxAge: c.Age.Max, //days
MaxSize: c.Size.Max, // megabytes
MaxBackups: c.Backup.Max,
Compress: true,
})
if err != nil {
return err
}
}
root = WithFields(fields...)
root.entry.Logger.Level = logLevel
root.entry.Logger.Out = logOutWriter
root.entry.Logger.Formatter = newFormatter(c.Format, true)
if fileHook != nil {
root.entry.Logger.Hooks.Add(fileHook)
}
return nil
}
// WithFields adds a map of fields to the Entry.
func WithFields(vs ...string) *Entry {
fs := logrus.Fields{}
for index := 0; index < len(vs)-1; index = index + 2 {
fs[vs[index]] = vs[index+1]
}
return &Entry{entry: root.entry.WithFields(fs)}
}
// WithError adds an error as single field (using the key defined in ErrorKey) to the Entry.
func WithError(err error) *Entry {
return &Entry{entry: root.entry.WithError(err)}
}
// // Debug log debug info
// func Debug(args ...interface{}) {
// root.entry.Debug(args...)
// }
// // Info log info
// func Info(args ...interface{}) {
// root.entry.Info(args...)
// }
// // Warn log warning info
// func Warn(args ...interface{}) {
// root.entry.Warn(args...)
// }
// // Error log error info
// func Error(args ...interface{}) {
// root.entry.Error(args...)
// }
// Debugf log debug info
func Debugf(format string, args ...interface{}) {
root.entry.Debugf(format, args...)
}
// Infof log info
func Infof(format string, args ...interface{}) {
root.entry.Infof(format, args...)
}
// Warnf log warning info
func Warnf(format string, args ...interface{}) {
root.entry.Warnf(format, args...)
}
// Errorf log error info
func Errorf(format string, args ...interface{}) {
root.entry.Errorf(format, args...)
}
// Debugln log debug info
func Debugln(args ...interface{}) {
root.entry.Debugln(args...)
}
// Infoln log info
func Infoln(args ...interface{}) {
root.entry.Infoln(args...)
}
// Warnln log warning info
func Warnln(args ...interface{}) {
root.entry.Warnln(args...)
}
// Errorln log error info
func Errorln(args ...interface{}) {
root.entry.Errorln(args...)
}
type fileConfig struct {
Filename string
MaxSize int
MaxAge int
MaxBackups int
LocalTime bool
Compress bool
Level logrus.Level
Formatter logrus.Formatter
}
type fileHook struct {
config fileConfig
writer io.Writer
}
func newFileHook(config fileConfig) (logrus.Hook, error) {
hook := fileHook{
config: config,
}
var zeroLevel logrus.Level
if hook.config.Level == zeroLevel {
hook.config.Level = logrus.InfoLevel
}
var zeroFormatter logrus.Formatter
if hook.config.Formatter == zeroFormatter {
hook.config.Formatter = new(logrus.TextFormatter)
}
hook.writer = &lumberjack.Logger{
Filename: config.Filename,
MaxSize: config.MaxSize,
MaxAge: config.MaxAge,
MaxBackups: config.MaxBackups,
LocalTime: config.LocalTime,
Compress: config.Compress,
}
return &hook, nil
}
// Levels Levels
func (hook *fileHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}
}
// Fire Fire
func (hook *fileHook) Fire(entry *logrus.Entry) (err error) {
if hook.config.Level < entry.Level {
return nil
}
b, err := hook.config.Formatter.Format(entry)
if err != nil {
return err
}
hook.writer.Write(b)
return nil
}
func newFormatter(format string, color bool) logrus.Formatter {
var formatter logrus.Formatter
if strings.ToLower(format) == "json" {
formatter = &logrus.JSONFormatter{}
} else {
if runtime.GOOS == "windows" {
color = false
}
formatter = &logrus.TextFormatter{FullTimestamp: true, DisableColors: !color}
}
return formatter
}
| true |
7d9ce6e88a38589a1dadaa87110d2be64bfff970
|
Go
|
houzhongjian/goss
|
/lib/utils.go
|
UTF-8
| 828 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
package lib
import (
"crypto/md5"
"encoding/hex"
"os"
"strconv"
"time"
)
func FileHash(body []byte) string {
h := md5.New()
h.Write(body)
b := h.Sum(nil)
return hex.EncodeToString(b)
}
//Hash .
func Hash(body string) []byte {
h := md5.New()
h.Write([]byte(body))
b := h.Sum(nil)
return []byte(hex.EncodeToString(b))
}
//IsExists 判断ini是否存在.
func IsExists(ini string) bool {
_, err := os.Stat(ini)
if err != nil {
return false
}
return true
}
//Time 获取当前时间.
func Time() string {
return time.Now().Format("2006-01-02 15:04:05")
}
//ParseInt .
func ParseInt(str string) int {
num, err := strconv.Atoi(str)
if err != nil {
return 0
}
return num
}
func InArray(item string, list []string) bool {
for _, v := range list {
if v == item {
return true
}
}
return false
}
| true |
8e2d8cd275d05fcf6a644d21d73b40e6a54d4bc6
|
Go
|
essentialkaos/ek
|
/sortutil/sortutil.go
|
UTF-8
| 2,384 | 3.390625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Package sortutil provides methods for sorting slices
package sortutil
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2023 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"sort"
"strconv"
"strings"
)
// ////////////////////////////////////////////////////////////////////////////////// //
type versionSlice []string
type stringSlice []string
// ////////////////////////////////////////////////////////////////////////////////// //
func (s versionSlice) Len() int { return len(s) }
func (s versionSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s versionSlice) Less(i, j int) bool {
return VersionCompare(s[i], s[j])
}
func (s stringSlice) Len() int { return len(s) }
func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s stringSlice) Less(i, j int) bool {
return strings.ToLower(s[i]) < strings.ToLower(s[j])
}
// ////////////////////////////////////////////////////////////////////////////////// //
// Versions sorts versions slice
func Versions(s []string) {
sort.Sort(versionSlice(s))
}
// VersionCompare compares 2 versions and returns true if v1 less v2. This function
// can be used for version sorting with structs
func VersionCompare(v1, v2 string) bool {
is := strings.Split(v1, ".")
js := strings.Split(v2, ".")
il, jl := len(is), len(js)
l := il
if jl > l {
l = jl
}
for k := 0; k < l; k++ {
switch {
case il-1 < k:
return true
case jl-1 < k:
return false
}
if is[k] == js[k] {
continue
}
ii, err1 := strconv.ParseInt(is[k], 10, 64)
ji, err2 := strconv.ParseInt(js[k], 10, 64)
if err1 != nil || err2 != nil {
return is[k] < js[k]
}
switch {
case ii < ji:
return true
case ii > ji:
return false
}
}
return true
}
// Strings sorts strings slice and support case insensitive mode
func Strings(s []string, caseInsensitive bool) {
if caseInsensitive {
sort.Sort(stringSlice(s))
} else {
sort.Strings(s)
}
}
| true |
a03251f0a4abe1c77b63bcd74590ef1ef3c8f25d
|
Go
|
sebastianvera/edd-lab1
|
/pregunta1/scraper/scraper.go
|
UTF-8
| 1,460 | 3.296875 | 3 |
[] |
no_license
|
[] |
no_license
|
package scraper
import (
"net/http"
"regexp"
"strings"
"golang.org/x/net/html"
)
const (
url = "http://www.sii.cl/pagina/valores/dolar/dolar2015.htm"
)
var (
commaToDot = strings.NewReplacer(",", ".")
summaryRegex = regexp.MustCompile("(?i)promedio")
)
// GetCSV returns a CSV string with the USD value in CLP currency
// for each day on an specific year.
// Each column represents the month of the year and each line
// represents the day of month.
func GetCSV() (string, error) {
res, err := makeRequest()
defer res.Body.Close()
doc, err := html.Parse(res.Body)
if err != nil {
return "", err
}
csv := ""
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "tr" && len(n.Attr) > 0 {
title := n.FirstChild.NextSibling.FirstChild.Data
if summaryRegex.MatchString(title) {
return
}
var vals []string
for s := n.FirstChild; s != nil; s = s.NextSibling {
if s.Type == html.ElementNode && s.Data == "td" {
value := commaToDot.Replace(strings.TrimSpace(s.FirstChild.Data))
vals = append(vals, value)
}
}
csv += strings.Join(vals, ",")
csv += "\n"
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
return strings.TrimSpace(csv), nil
}
func makeRequest() (*http.Response, error) {
client := http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return client.Do(req)
}
| true |
be81ae149520f08b8979794da603592b0a06d15f
|
Go
|
AlphaBeta906/Nv7Haven
|
/eod/sorts.go
|
UTF-8
| 2,379 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package eod
import (
"sort"
"strconv"
"github.com/Nv7-Github/Nv7Haven/eod/types"
"github.com/bwmarrin/discordgo"
)
var sortChoices = []*discordgo.ApplicationCommandOptionChoice{
{
Name: "Name",
Value: "name",
},
{
Name: "Length",
Value: "length",
},
{
Name: "Date Created",
Value: "createdon",
},
{
Name: "Complexity",
Value: "complexity",
},
{
Name: "Difficulty",
Value: "difficulty",
},
{
Name: "Used In",
Value: "usedin",
},
{
Name: "Creator",
Value: "creator",
},
}
var sorts = map[string]func(a, b string, dat types.ServerData) bool{
"length": func(a, b string, dat types.ServerData) bool {
return len(a) < len(b)
},
"name": func(a, b string, dat types.ServerData) bool {
return compareStrings(a, b)
},
"createdon": func(a, b string, dat types.ServerData) bool {
el1, res := dat.GetElement(a, true)
el2, res2 := dat.GetElement(b, true)
if !res.Exists || !res2.Exists {
return false
}
return el1.CreatedOn.Before(el2.CreatedOn)
},
"complexity": func(a, b string, dat types.ServerData) bool {
el1, res := dat.GetElement(a, true)
el2, res2 := dat.GetElement(b, true)
if !res.Exists || !res2.Exists {
return false
}
return el1.Complexity < el2.Complexity
},
"difficulty": func(a, b string, dat types.ServerData) bool {
el1, res := dat.GetElement(a, true)
el2, res2 := dat.GetElement(b, true)
if !res.Exists || !res2.Exists {
return false
}
return el1.Difficulty < el2.Difficulty
},
"usedin": func(a, b string, dat types.ServerData) bool {
el1, res := dat.GetElement(a, true)
el2, res2 := dat.GetElement(b, true)
if !res.Exists || !res2.Exists {
return false
}
return el1.UsedIn < el2.UsedIn
},
"creator": func(a, b string, dat types.ServerData) bool {
el1, res := dat.GetElement(a, true)
el2, res2 := dat.GetElement(b, true)
if !res.Exists || !res2.Exists {
return false
}
return el1.Creator < el2.Creator
},
}
// Less
func compareStrings(a, b string) bool {
fl1, err := strconv.ParseFloat(a, 32)
fl2, err2 := strconv.ParseFloat(b, 32)
if err == nil && err2 == nil {
return fl1 < fl2
}
return a < b
}
func sortElemList(elems []string, sortName string, dat types.ServerData) {
sorter := sorts[sortName]
dat.Lock.RLock()
sort.Slice(elems, func(i, j int) bool {
return sorter(elems[i], elems[j], dat)
})
dat.Lock.RUnlock()
}
| true |
1ab212fcb163f1157830d099f4e56e2143d41433
|
Go
|
DiegoSantosWS/workshop
|
/dia_03/exemplos/server08.go
|
UTF-8
| 3,993 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"time"
)
type cep struct {
Cep string `json:"cep"`
Cidade string `json:"cidade,omitempty"`
Bairro string `json:"bairro,omitempty"`
Logradouro string `json:"logradouro,omitempty"`
UF string `json:"uf,omitempty"`
}
func (c cep) exist() bool {
return len(c.UF) != 0
}
var endpoints = map[string]string{
"viacep": "https://viacep.com.br/ws/%s/json/",
"postmon": "https://api.postmon.com.br/v1/cep/%s",
"republicavirtual": "https://republicavirtual.com.br/web_cep.php?cep=%s&formato=json",
}
func home(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Write([]byte("Bem vindo a API de CEPs"))
}
func cepHandler(w http.ResponseWriter, r *http.Request) {
// Restrigindo o acesso apenas pelo método GET
if r.Method != http.MethodGet {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
rCep := r.URL.Path[len("/cep/"):]
// Validando o CEP
rCep, err := sanitizeCEP(rCep)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ch := make(chan []byte, 1)
for src, url := range endpoints {
endpoint := fmt.Sprintf(url, rCep)
go request(endpoint, src, rCep, ch)
}
w.Header().Set("Content-Type", "application/json")
for index := 0; index < 3; index++ {
log.Println(index)
cepInfo, err := parseResponse(<-ch)
if err != nil {
continue
}
if cepInfo.exist() {
cepInfo.Cep = rCep
json.NewEncoder(w).Encode(cepInfo)
return
}
}
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
}
func request(endpoint, src, cep string, ch chan []byte) {
start := time.Now()
c := http.Client{Timeout: time.Duration(time.Millisecond * 300)}
resp, err := c.Get(endpoint)
if err != nil {
log.Printf("Ops! ocorreu um erro: %s", err.Error())
ch <- nil
return
}
defer resp.Body.Close()
requestContent, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Ops! ocorreu um erro: %s", err.Error())
ch <- nil
return
}
if len(requestContent) != 0 && resp.StatusCode == http.StatusOK {
log.Printf("O endpoint respondeu com sucesso - source: %s, CEP: %s, Duração: %s", src, cep, time.Since(start).String())
ch <- requestContent
}
}
func parseResponse(content []byte) (payload cep, err error) {
response := make(map[string]interface{})
_ = json.Unmarshal(content, &response)
if err := isValidResponse(response); !err {
return payload, errors.New("invalid response")
}
if _, ok := response["localidade"]; ok {
payload.Cidade = response["localidade"].(string)
} else {
payload.Cidade = response["cidade"].(string)
}
if _, ok := response["estado"]; ok {
payload.UF = response["estado"].(string)
} else {
payload.UF = response["uf"].(string)
}
if _, ok := response["logradouro"]; ok {
payload.Logradouro = response["logradouro"].(string)
}
if _, ok := response["tipo_logradouro"]; ok {
payload.Logradouro = response["tipo_logradouro"].(string) + " " + payload.Logradouro
}
payload.Bairro = response["bairro"].(string)
return
}
func isValidResponse(requestContent map[string]interface{}) bool {
if len(requestContent) <= 0 {
return false
}
if _, ok := requestContent["erro"]; ok {
return false
}
if _, ok := requestContent["fail"]; ok {
return false
}
return true
}
// Função para validar o CEP
func sanitizeCEP(cep string) (string, error) {
re := regexp.MustCompile(`[^0-9]`)
sanitizedCEP := re.ReplaceAllString(cep, `$1`)
if len(sanitizedCEP) < 8 {
return "", errors.New("O CEP deve conter apenas números e no minimo 8 digitos")
}
return sanitizedCEP[:8], nil
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", home)
mux.HandleFunc("/cep/", cepHandler)
log.Println("Iniciando o servidor na porta: 4000")
err := http.ListenAndServe(":4000", mux)
log.Fatal(err)
}
| true |
5eba0869ac67f97a0a56d451cec8a7437707a98c
|
Go
|
andrewbackes/autonoma
|
/pkg/perception/perception.go
|
UTF-8
| 834 | 2.765625 | 3 |
[] |
no_license
|
[] |
no_license
|
// Package perception uses sensor data to create an understanding the environment around the robot as well as the robot's position in that environment.
package perception
import (
"github.com/andrewbackes/autonoma/pkg/pointcloud"
"github.com/andrewbackes/autonoma/pkg/vector"
)
// Perception of the vehicle given sensor data.
type Perception struct {
EnvironmentModel EnvironmentModel `json:"environmentModel"`
DrivableSurface Surface `json:"drivableSurface"`
Vehicle Vehicle `json:"vehicle"`
Path []vector.Vector `json:"path"`
Scans [][]vector.Vector `json:"scans"`
}
func New() *Perception {
return &Perception{
EnvironmentModel: EnvironmentModel{
PointCloud: pointcloud.New(),
},
Path: make([]vector.Vector, 0),
Scans: make([][]vector.Vector, 0),
}
}
| true |
4eee69d54b654b808ba224edd0f444844137d840
|
Go
|
dranidis/the-way-to-go
|
/eval/eval.go
|
UTF-8
| 331 | 3.4375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
// M OMIT
func Eval(f func(int) int, x int) int {
return f(x)
}
func square(x int) int {
return x * x
}
func main() {
fmt.Println(Eval(square, 2))
increase := func(x int) int { return x+1}
fmt.Println(Eval(increase, 0))
fmt.Println(Eval(func(x int) int {return x * x * x}, 2))
}
// END OMIT
| true |
56620b49f0873836e3511ed982703b46a0bd7a9a
|
Go
|
liujiahavefun/FishChatServer2
|
/common/net/xweb/router.go
|
UTF-8
| 3,002 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package xweb
import (
"FishChatServer2/common/net/trace"
"FishChatServer2/common/net/xweb/context"
ctx "golang.org/x/net/context"
"net/http"
)
const (
_family = "go_http_server"
)
// web http pattern router
type Router struct {
mux *http.ServeMux
pattern string
}
// NewRouter new a router.
func NewRouter(mux *http.ServeMux) *Router {
return &Router{mux: mux}
}
func (r *Router) join(pattern string) string {
return r.pattern + pattern
}
func (r *Router) Group(pattern string) *Router {
return &Router{mux: r.mux, pattern: r.join(pattern)}
}
// Handler is an adapter which allows the usage of an http.Handler as a
// request handle.
func (r *Router) Handle(method, pattern string, handlers ...Handler) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handler(method, w, r, handlers)
})
return
}
func (r *Router) HandlerFunc(method, pattern string, handlers ...HandlerFunc) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handleFunc(method, w, r, handlers)
})
return
}
// Get is a shortcut for router.Handle("GET", path, handle)
func (r *Router) Get(pattern string, handlers ...Handler) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handler("GET", w, r, handlers)
})
return
}
func (r *Router) Post(pattern string, handlers ...Handler) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handler("POST", w, r, handlers)
})
return
}
// GetFunc is a shortcut for router.HandleFunc("GET", path, handle)
func (r *Router) GetFunc(pattern string, handlers ...HandlerFunc) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handleFunc("GET", w, r, handlers)
})
return
}
// PostFunc is a shortcut for router.HandleFunc("GET", path, handle)
func (r *Router) PostFunc(pattern string, handlers ...HandlerFunc) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handleFunc("POST", w, r, handlers)
})
return
}
func handler(method string, w http.ResponseWriter, r *http.Request, handlers []Handler) {
t := trace.WithHTTP(r)
t.ServerReceive(_family, r.URL.Path, "")
defer t.ServerSend()
if r.Method != method {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
c := context.NewContext(trace.NewContext(ctx.Background(), t), r, w)
for _, h := range handlers {
h.ServeHTTP(c)
if err := c.Err(); err != nil {
break
}
}
}
func handleFunc(method string, w http.ResponseWriter, r *http.Request, handlers []HandlerFunc) {
t := trace.WithHTTP(r)
t.ServerReceive(_family, r.URL.Path, "")
defer t.ServerSend()
if r.Method != method {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
c := context.NewContext(trace.NewContext(ctx.Background(), t), r, w)
for _, h := range handlers {
h(c)
if err := c.Err(); err != nil {
break
}
}
}
| true |
871491982f9bbf114271bbe57768df191e09e0ec
|
Go
|
gregoryv/fox
|
/synclog.go
|
UTF-8
| 595 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package fox
import (
"fmt"
"io"
"sync"
)
func NewSyncLog(w io.Writer) *SyncLog {
return &SyncLog{w: w}
}
type SyncLog struct {
mu sync.Mutex
w io.Writer
}
// Log synchronizes calls to the underlying writer and makes sure
// each message ends with one new line
func (l *SyncLog) Log(v ...interface{}) {
l.mu.Lock()
fmt.Fprintln(l.w, v...)
l.mu.Unlock()
}
func (l *SyncLog) SetOutput(w io.Writer) {
l.mu.Lock()
l.w = w
l.mu.Unlock()
}
// FilterEmpty returns a wrapper filtering out empty and nil values
func (l *SyncLog) FilterEmpty() *FilterEmpty {
return NewFilterEmpty(l)
}
| true |
e7664cb8d7366bbad0513b7e6e73a9c41dea52d1
|
Go
|
slimsag/mega
|
/influxdb/tsdb/show_measurements.go
|
UTF-8
| 5,991 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package tsdb
import (
"encoding/json"
"fmt"
"sort"
"github.com/influxdb/influxdb/influxql"
)
// ShowMeasurementsExecutor implements the Executor interface for a SHOW MEASUREMENTS statement.
type ShowMeasurementsExecutor struct {
stmt *influxql.ShowMeasurementsStatement
mappers []Mapper
chunkSize int
}
// NewShowMeasurementsExecutor returns a new ShowMeasurementsExecutor.
func NewShowMeasurementsExecutor(stmt *influxql.ShowMeasurementsStatement, mappers []Mapper, chunkSize int) *ShowMeasurementsExecutor {
return &ShowMeasurementsExecutor{
stmt: stmt,
mappers: mappers,
chunkSize: chunkSize,
}
}
// Execute begins execution of the query and returns a channel to receive rows.
func (e *ShowMeasurementsExecutor) Execute() <-chan *influxql.Row {
// Create output channel and stream data in a separate goroutine.
out := make(chan *influxql.Row, 0)
go func() {
// Open the mappers.
for _, m := range e.mappers {
if err := m.Open(); err != nil {
out <- &influxql.Row{Err: err}
return
}
}
// Create a set to hold measurement names from mappers.
set := map[string]struct{}{}
// Iterate through mappers collecting measurement names.
for _, m := range e.mappers {
// Get the data from the mapper.
c, err := m.NextChunk()
if err != nil {
out <- &influxql.Row{Err: err}
return
} else if c == nil {
// Mapper had no data.
continue
}
// Convert the mapper chunk to a string array of measurement names.
mms, ok := c.([]string)
if !ok {
out <- &influxql.Row{Err: fmt.Errorf("show measurements mapper returned invalid type: %T", c)}
return
}
// Add the measurement names to the set.
for _, mm := range mms {
set[mm] = struct{}{}
}
}
// Convert the set into an array of measurement names.
measurements := make([]string, 0, len(set))
for mm := range set {
measurements = append(measurements, mm)
}
// Sort the names.
sort.Strings(measurements)
// Calculate OFFSET and LIMIT
off := e.stmt.Offset
lim := len(measurements)
stmtLim := e.stmt.Limit
if stmtLim > 0 && off+stmtLim < lim {
lim = off + stmtLim
} else if off > lim {
off, lim = 0, 0
}
// Put the results in a row and send it.
row := &influxql.Row{
Name: "measurements",
Columns: []string{"name"},
Values: make([][]interface{}, 0, len(measurements)),
}
for _, m := range measurements[off:lim] {
v := []interface{}{m}
row.Values = append(row.Values, v)
}
if len(row.Values) > 0 {
out <- row
}
close(out)
// It's important that all resources are released when execution completes.
e.close()
}()
return out
}
// Close closes the executor such that all resources are released. Once closed,
// an executor may not be re-used.
func (e *ShowMeasurementsExecutor) close() {
if e != nil {
for _, m := range e.mappers {
m.Close()
}
}
}
// ShowMeasurementsMapper is a mapper for collecting measurement names from a shard.
type ShowMeasurementsMapper struct {
remote Mapper
shard *Shard
stmt *influxql.ShowMeasurementsStatement
chunkSize int
state interface{}
}
// NewShowMeasurementsMapper returns a mapper for the given shard, which will return data for the meta statement.
func NewShowMeasurementsMapper(shard *Shard, stmt *influxql.ShowMeasurementsStatement, chunkSize int) *ShowMeasurementsMapper {
return &ShowMeasurementsMapper{
shard: shard,
stmt: stmt,
chunkSize: chunkSize,
}
}
// Open opens the mapper for use.
func (m *ShowMeasurementsMapper) Open() error {
if m.remote != nil {
return m.remote.Open()
}
var measurements Measurements
if m.shard != nil {
// If a WHERE clause was specified, filter the measurements.
if m.stmt.Condition != nil {
var err error
measurements, err = m.shard.index.measurementsByExpr(m.stmt.Condition)
if err != nil {
return err
}
} else {
// Otherwise, get all measurements from the database.
measurements = m.shard.index.Measurements()
}
sort.Sort(measurements)
}
// Create a channel to send measurement names on.
ch := make(chan string)
// Start a goroutine to send the names over the channel as needed.
go func() {
for _, mm := range measurements {
ch <- mm.Name
}
close(ch)
}()
// Store the channel as the state of the mapper.
m.state = ch
return nil
}
// SetRemote sets the remote mapper to use.
func (m *ShowMeasurementsMapper) SetRemote(remote Mapper) error {
m.remote = remote
return nil
}
// TagSets is only implemented on this mapper to satisfy the Mapper interface.
func (m *ShowMeasurementsMapper) TagSets() []string { return nil }
// Fields returns a list of field names for this mapper.
func (m *ShowMeasurementsMapper) Fields() []string { return []string{"name"} }
// NextChunk returns the next chunk of measurement names.
func (m *ShowMeasurementsMapper) NextChunk() (interface{}, error) {
if m.remote != nil {
b, err := m.remote.NextChunk()
if err != nil {
return nil, err
} else if b == nil {
return nil, nil
}
names := []string{}
if err := json.Unmarshal(b.([]byte), &names); err != nil {
return nil, err
} else if len(names) == 0 {
// Mapper on other node sent 0 values so it's done.
return nil, nil
}
return names, nil
}
return m.nextChunk()
}
// nextChunk implements next chunk logic for a local shard.
func (m *ShowMeasurementsMapper) nextChunk() (interface{}, error) {
// Allocate array to hold measurement names.
names := make([]string, 0, m.chunkSize)
// Get the channel of measurement names from the state.
measurementNames := m.state.(chan string)
// Get the next chunk of names.
for n := range measurementNames {
names = append(names, n)
if len(names) == m.chunkSize {
break
}
}
// See if we've read all the names.
if len(names) == 0 {
return nil, nil
}
return names, nil
}
// Close closes the mapper.
func (m *ShowMeasurementsMapper) Close() {
if m.remote != nil {
m.remote.Close()
}
}
| true |
8d68122684fbc7a39d75f907768e86d3cd8f005b
|
Go
|
owncast/owncast
|
/controllers/auth/indieauth/client.go
|
UTF-8
| 3,063 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package indieauth
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/owncast/owncast/auth"
ia "github.com/owncast/owncast/auth/indieauth"
"github.com/owncast/owncast/controllers"
"github.com/owncast/owncast/core/chat"
"github.com/owncast/owncast/core/user"
log "github.com/sirupsen/logrus"
)
// StartAuthFlow will begin the IndieAuth flow for the current user.
func StartAuthFlow(u user.User, w http.ResponseWriter, r *http.Request) {
type request struct {
AuthHost string `json:"authHost"`
}
type response struct {
Redirect string `json:"redirect"`
}
var authRequest request
p, err := io.ReadAll(r.Body)
if err != nil {
controllers.WriteSimpleResponse(w, false, err.Error())
return
}
if err := json.Unmarshal(p, &authRequest); err != nil {
controllers.WriteSimpleResponse(w, false, err.Error())
return
}
accessToken := r.URL.Query().Get("accessToken")
redirectURL, err := ia.StartAuthFlow(authRequest.AuthHost, u.ID, accessToken, u.DisplayName)
if err != nil {
controllers.WriteSimpleResponse(w, false, err.Error())
return
}
redirectResponse := response{
Redirect: redirectURL.String(),
}
controllers.WriteResponse(w, redirectResponse)
}
// HandleRedirect will handle the redirect from an IndieAuth server to
// continue the auth flow.
func HandleRedirect(w http.ResponseWriter, r *http.Request) {
state := r.URL.Query().Get("state")
code := r.URL.Query().Get("code")
request, response, err := ia.HandleCallbackCode(code, state)
if err != nil {
log.Debugln(err)
msg := `Unable to complete authentication. <a href="/">Go back.</a><hr/>`
_ = controllers.WriteString(w, msg, http.StatusBadRequest)
return
}
// Check if a user with this auth already exists, if so, log them in.
if u := auth.GetUserByAuth(response.Me, auth.IndieAuth); u != nil {
// Handle existing auth.
log.Debugln("user with provided indieauth already exists, logging them in")
// Update the current user's access token to point to the existing user id.
accessToken := request.CurrentAccessToken
userID := u.ID
if err := user.SetAccessTokenToOwner(accessToken, userID); err != nil {
controllers.WriteSimpleResponse(w, false, err.Error())
return
}
if request.DisplayName != u.DisplayName {
loginMessage := fmt.Sprintf("**%s** is now authenticated as **%s**", request.DisplayName, u.DisplayName)
if err := chat.SendSystemAction(loginMessage, true); err != nil {
log.Errorln(err)
}
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
// Otherwise, save this as new auth.
log.Debug("indieauth token does not already exist, saving it as a new one for the current user")
if err := auth.AddAuth(request.UserID, response.Me, auth.IndieAuth); err != nil {
controllers.WriteSimpleResponse(w, false, err.Error())
return
}
// Update the current user's authenticated flag so we can show it in
// the chat UI.
if err := user.SetUserAsAuthenticated(request.UserID); err != nil {
log.Errorln(err)
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
| true |
15ae77e2790950c752138c30dc284d18fe65eacc
|
Go
|
ngyuki/go-traphandle
|
/match/condition.go
|
UTF-8
| 939 | 3.375 | 3 |
[] |
no_license
|
[] |
no_license
|
package match
import (
"fmt"
"regexp"
)
type Condition interface {
IsMatch(string) bool
}
type callbackCondition struct {
callback func(v string) bool
not bool
}
func (c *callbackCondition) IsMatch(v string) bool {
return c.callback(v)
}
func newCondition(op string, vals []string) Condition {
switch op {
case "eq", "not_eq":
vmap := make(map[string]bool)
for _, v := range vals {
vmap[v] = true
}
callback := func(v string) bool {
return vmap[v]
}
return &callbackCondition{callback, op == "not_eq"}
case "regexp", "not_regexp":
regs := make([]*regexp.Regexp, 0)
for _, v := range vals {
regs = append(regs, regexp.MustCompile(v))
}
callback := func(v string) bool {
for _, r := range regs {
if r.MatchString(v) == false {
return false
}
}
return true
}
return &callbackCondition{callback, op == "not_regexp"}
}
panic(fmt.Errorf("Unknown condition %v", op))
}
| true |
af1312ba0e0239ebf9be2f40c947d0894c79cbe8
|
Go
|
patrick-higgins/gitexport
|
/lex/lex_test.go
|
UTF-8
| 3,638 | 3.328125 | 3 |
[] |
no_license
|
[] |
no_license
|
package lex
import (
"bytes"
"io"
"reflect"
"strings"
"testing"
)
func TestClassify(t *testing.T) {
for i, tt := range []struct {
line string
err error
want Token
}{
// Lines must have an LF
{"data", nil, InvalidTok},
{"data ", nil, InvalidTok},
{"data arg1", nil, InvalidTok},
{"data arg1 arg2", nil, InvalidTok},
// Arguments are allowed
{"data\n", nil, DataTok},
{"data arg1\n", nil, DataTok},
{"data arg1 arg2\n", nil, DataTok},
// Unknown commands are invalid
{"foo\n", nil, InvalidTok},
// Comments
{"#", nil, CommentTok},
{"#a", nil, CommentTok},
{"#a\n", nil, CommentTok},
{"# a", nil, CommentTok},
{"# a\n", nil, CommentTok},
// Errors are ignored if the line isn't empty
{"\n", io.EOF, EmptyTok},
{"data\n", io.EOF, DataTok},
{"data\n", io.ErrClosedPipe, DataTok},
// Errors are returned when line is empty
{"", io.EOF, EOFTok},
{"", io.ErrClosedPipe, ErrTok},
} {
got := classify(tt.line, tt.err)
if got != tt.want {
t.Errorf("[%d] classify(%#v, %#v)=%v, want=%v", i, tt.line, tt.err, got, tt.want)
}
}
}
func TestLex(t *testing.T) {
r := strings.NewReader(strings.Replace(`reset refs/heads/a
commit refs/heads/a
mark :1
author Some Guy <[email protected]> 1393367434 -0700
committer Some Guy <[email protected]> 1393367434 -0700
M 100644 e79c5e8f964493290a409888d5413a737e8e5dd5 test.txt
reset refs/heads/master
from :2
# a comment
tag c.Merge-to-a-1
#another comment
from :2
tagger Some Guy <[email protected]> 1393367459 -0700
`, "\r\n", "\n", -1))
l := New(r)
for i, tt := range []struct {
tok Token
fields []string
}{
{ResetTok, []string{"reset", "refs/heads/a"}},
{CommitTok, []string{"commit", "refs/heads/a"}},
{MarkTok, []string{"mark", ":1"}},
{AuthorTok, []string{"author", "Some", "Guy", "<[email protected]>", "1393367434", "-0700"}},
{CommitterTok, []string{"committer", "Some", "Guy", "<[email protected]>", "1393367434", "-0700"}},
{MTok, []string{"M", "100644", "e79c5e8f964493290a409888d5413a737e8e5dd5", "test.txt"}},
{EmptyTok, []string{""}},
{ResetTok, []string{"reset", "refs/heads/master"}},
{FromTok, []string{"from", ":2"}},
{EmptyTok, []string{""}},
{CommentTok, []string{"#", "a", "comment"}},
{TagTok, []string{"tag", "c.Merge-to-a-1"}},
{CommentTok, []string{"#another", "comment"}},
{FromTok, []string{"from", ":2"}},
{TaggerTok, []string{"tagger", "Some", "Guy", "<[email protected]>", "1393367459", "-0700"}},
{EmptyTok, []string{""}},
{EOFTok, nil},
} {
tok := l.Token()
fields := l.Fields()
if tok != tt.tok {
t.Errorf("[%d]: token got=%v, want=%v", i, tok, tt.tok)
}
if !reflect.DeepEqual(fields, tt.fields) {
t.Errorf("[%d]: fields got=%#v, want=%#v", i, fields, tt.fields)
}
l.Consume()
}
}
func TestData(t *testing.T) {
for i, tt := range []struct {
data string
want []byte
lineNumber int
err bool
}{
// Simple case
{"data 3\nfoo", []byte("foo"), 2, false},
// Error on short read
{"data 4\nfoo", nil, 1, true},
// Increment line number for each \n
{"data 12\nfoo\nbar\nbaz\n", []byte("foo\nbar\nbaz\n"), 5, false},
// Delimited format
{"data <<EOF\nfoo\nEOF\n", []byte("foo\n"), 4, false},
} {
r := strings.NewReader(tt.data)
l := New(r)
got, err := l.ConsumeData()
if tt.err && err == nil {
t.Errorf("[%d] expected error but didn't get one", i)
}
if !tt.err && err != nil {
t.Errorf("[%d] error: %v", i, err)
}
if !bytes.Equal(got, tt.want) {
t.Errorf("[%d] got=%v, want=%v", i, got, tt.want)
}
if l.LineNumber() != tt.lineNumber {
t.Errorf("[%d] lineNumber=%v, want=%v", i, l.LineNumber(), tt.lineNumber)
}
}
}
| true |
27f644ea03464df1ff4e6bc4b1bd5f06d23823c9
|
Go
|
reonard/config-publisher
|
/lib/config.go
|
UTF-8
| 647 | 2.703125 | 3 |
[] |
no_license
|
[] |
no_license
|
package lib
import (
"fmt"
"github.com/go-ini/ini"
)
type AppConfig struct {
KafkaBrokers []string
ConsumerGroupID string
AlarmTopics []string
MongodbURL string
WorkerNum int
BulkDataBuffer int
MySqlURL string
}
var AppCfg = AppConfig{}
func InitCfg() {
iniFile, err := ini.Load("./config.ini")
if err != nil {
panic("读取配置失败")
}
mapTo(iniFile, "app", &AppCfg)
}
func mapTo(iniFile *ini.File, section string, v interface{}) {
err := iniFile.Section(section).MapTo(v)
if err != nil {
panic(fmt.Sprintf("mapTo %s: Setting Error", section))
}
fmt.Printf("%s: %+v \n", section, v)
}
| true |
292185aa70cde6c773cefb1da539e0a94dde0076
|
Go
|
mithro/luci-go
|
/common/chunkstream/chunk_test.go
|
UTF-8
| 1,339 | 3.015625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2015 The LUCI Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
package chunkstream
import (
"fmt"
"strings"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
type testChunk struct {
data []byte
released bool
}
var _ Chunk = (*testChunk)(nil)
func tc(d ...byte) *testChunk {
return &testChunk{
data: d,
}
}
func (c *testChunk) String() string {
pieces := make([]string, len(c.data))
for i, d := range c.data {
pieces[i] = fmt.Sprintf("0x%02x", d)
}
return fmt.Sprintf("{%s}", strings.Join(pieces, ", "))
}
func (c *testChunk) Bytes() []byte {
return c.data
}
func (c *testChunk) Len() int {
return len(c.data)
}
func (c *testChunk) Release() {
if c.released {
panic("double-free")
}
c.released = true
}
func TestChunkNode(t *testing.T) {
Convey(`A chunkNode wrapping a testing Chunk implementation`, t, func() {
c := tc(0, 1, 2)
n := newChunkNode(c)
Convey(`Should call Chunk methods.`, func() {
So(n.Bytes(), ShouldResemble, []byte{0, 1, 2})
})
Convey(`When released, releases the wrapped Chunk.`, func() {
n.release()
So(c.released, ShouldBeTrue)
Convey(`If released again, panics.`, func() {
So(func() { n.release() }, ShouldPanic)
})
})
})
}
| true |
fd09f093cac7f9b35d3e4d2ee865ff70e9cf796c
|
Go
|
baotianjiazhi/leetcode-and-offer
|
/src/剑指offer/剑指 Offer 10- II. 青蛙跳台阶问题.go
|
UTF-8
| 241 | 2.625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
func numWays(n int) int {
if n == 0 {
return 1
}
if n == 1 {
return 1
}
if n == 2 {
return 2
}
dp := []int{1, 1, 2}
for i := 3; i <= n; i++ {
dp = append(dp, (dp[i-1]+dp[i-2])%1000000007)
}
return dp[n]
}
| true |
ec126d6a84434be7091e2b5d21a3b3f0c4b6316d
|
Go
|
martinohmann/kubectl-chart
|
/pkg/resources/interfaces.go
|
UTF-8
| 520 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package resources
import "k8s.io/apimachinery/pkg/runtime"
// Encoder is the interface for an encoder that encodes multiple objects as
// slices of bytes.
type Encoder interface {
// Encode encodes slices of runtime.Object as bytes.
Encode(objs []runtime.Object) ([]byte, error)
}
// Decoder is the interface of something that can decode raw bytes into slices
// of runtime.Object.
type Decoder interface {
// Decode decodes raw bytes into slices of runtime.Object.
Decode(raw []byte) ([]runtime.Object, error)
}
| true |
dd14148e5167cb391b611cf5a395cf23b2680e8a
|
Go
|
mmirolim/gpp
|
/testdata/try/main.go
|
UTF-8
| 1,334 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"errors"
"fmt"
mcr "github.com/mmirolim/gpp/macro"
"gpp.com/try/lib"
)
func main() {
slf := []func() error{func() error { return nil }}
var result int
err := mcr.Try_μ(func() error {
fname, _ := fStrError(false)
_, result, _ = fPtrIntError(false)
slf[0]()
NoErrReturn()
if result == 1 {
// should return here
fErr(true)
}
// should not reach here
fmt.Printf("fname %+v\n", fname) // output for debug
err := errors.New("some custom error")
return err
})
fmt.Println("")
fmt.Printf("(result, err) = (%d, %+v)\n", result, err)
var recs [][]string
var bs []*lib.B
err = mcr.Try_μ(func() error {
_, _ = fStrError(false)
_, result, _ = fPtrIntError(false)
fErr(false)
mcr.NewSeq_μ(recs).Map(lib.NewB).Ret(&bs)
// should return here
return nil
})
fmt.Printf("(result, err) = (%d, %+v)\n", result, err)
}
func NoErrReturn() string {
return "return is not an error"
}
func fStrError(toError bool) (string, error) {
if toError {
return "", errors.New("fStrError error")
}
return "fStrError", nil
}
func fErr(toError bool) error {
if toError {
return errors.New("fErr error")
}
return nil
}
type A struct{}
func fPtrIntError(toError bool) (*A, int, error) {
if toError {
return nil, 0, errors.New("fPtrIntError error")
}
return &A{}, 1, nil
}
| true |
798bebb3c859410a570473912580a6eee9062358
|
Go
|
ookayama-playgrounds/go-playgrounds
|
/echo/handler/handler_test.go
|
UTF-8
| 2,596 | 2.828125 | 3 |
[] |
no_license
|
[] |
no_license
|
package handler
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
var (
mockDB = map[string]*User{
"[email protected]": &User{"Jon Snow", "[email protected]"},
"[email protected]": &User{"Bob Leaves", "[email protected]"},
}
errorMockDB = map[string]*User{}
userJSON = `{"name":"Jon Snow","email":"[email protected]"}`
errorUserJSON = `{"msr:Jon Snow","rso;":"[email protected]"}`
usersJSON = `{{"name":"Jon Snow","email":"[email protected]"},{"name":"Bob Leaves","email":"[email protected]"}}`
)
/*
正常系のテスト
*/
func TestInsertHello(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/hey", strings.NewReader(userJSON))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
cache = mockDB
// Assertions
if assert.NoError(t, InsertHello(c)) {
assert.Equal(t, http.StatusCreated, rec.Code)
// assert.Equal(t, userJSON, rec.Body.String())
}
}
func TestGetHello(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/hey", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
c.SetPath("/hey/:email")
c.SetParamNames("email")
c.SetParamValues("[email protected]")
cache = mockDB
// Assertions
if assert.NoError(t, GetHello(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
// assert.Equal(t, userJSON, rec.Body.String())
}
}
func TestHello(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/hello", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
cache = mockDB
// Assertions
if assert.NoError(t, Hello(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
// assert.Equal(t, userJSON, rec.Body.String())
}
}
/*
異常系テスト
*/
func TestInsertHelloNoParams(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/hey", strings.NewReader(errorUserJSON))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
cache = map[string]*User{}
// Assertions
if assert.Error(t, InsertHello(c)) {
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
}
func TestGetHelloNoParams(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/hey", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
c.SetPath("/hey/:email")
c.SetParamNames("email")
c.SetParamValues("[email protected]")
cache = map[string]*User{}
// Assertions
if assert.Error(t, GetHello(c)) {
assert.Equal(t, http.StatusNotFound, rec.Code)
}
}
| true |
12096b73e0eca0cae0f08112365ed40829dd46ec
|
Go
|
ansible-semaphore/semaphore
|
/db/sql/schedule.go
|
UTF-8
| 2,246 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package sql
import (
"database/sql"
"github.com/ansible-semaphore/semaphore/db"
)
func (d *SqlDb) CreateSchedule(schedule db.Schedule) (newSchedule db.Schedule, err error) {
insertID, err := d.insert(
"id",
"insert into project__schedule (project_id, template_id, cron_format, repository_id)"+
"values (?, ?, ?, ?)",
schedule.ProjectID,
schedule.TemplateID,
schedule.CronFormat,
schedule.RepositoryID)
if err != nil {
return
}
newSchedule = schedule
newSchedule.ID = insertID
return
}
func (d *SqlDb) SetScheduleLastCommitHash(projectID int, scheduleID int, lastCommentHash string) error {
_, err := d.exec("update project__schedule set "+
"last_commit_hash=? "+
"where project_id=? and id=?",
lastCommentHash,
projectID,
scheduleID)
return err
}
func (d *SqlDb) UpdateSchedule(schedule db.Schedule) error {
_, err := d.exec("update project__schedule set "+
"cron_format=?, "+
"repository_id=?, "+
"last_commit_hash = NULL "+
"where project_id=? and id=?",
schedule.CronFormat,
schedule.RepositoryID,
schedule.ProjectID,
schedule.ID)
return err
}
func (d *SqlDb) GetSchedule(projectID int, scheduleID int) (template db.Schedule, err error) {
err = d.selectOne(
&template,
"select * from project__schedule where project_id=? and id=?",
projectID,
scheduleID)
if err == sql.ErrNoRows {
err = db.ErrNotFound
}
return
}
func (d *SqlDb) DeleteSchedule(projectID int, scheduleID int) error {
_, err := d.exec("delete from project__schedule where project_id=? and id=?", projectID, scheduleID)
return err
}
func (d *SqlDb) GetSchedules() (schedules []db.Schedule, err error) {
_, err = d.selectAll(&schedules, "select * from project__schedule where cron_format != ''")
return
}
func (d *SqlDb) GetTemplateSchedules(projectID int, templateID int) (schedules []db.Schedule, err error) {
_, err = d.selectAll(&schedules,
"select * from project__schedule where project_id=? and template_id=?",
projectID,
templateID)
return
}
func (d *SqlDb) SetScheduleCommitHash(projectID int, scheduleID int, hash string) error {
_, err := d.exec("update project__schedule set last_commit_hash=? where project_id=? and id=?",
hash,
projectID,
scheduleID)
return err
}
| true |
245a44dd5660bdd98a73e4032da9b9eaa3043dfa
|
Go
|
bubu4me/Go-Fundamental
|
/Projects/v09_task.go
|
UTF-8
| 3,111 | 4.25 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
func main() {
// A(10) // 10
// fmt.Println(B(10)) // 10 10
// fmt.Println(C(10, 11)) // 10 11
// D(1, 2) // [1 2]
// D(1, 2, 3, 4, 5) // [1 2 3 4 5]
// // 值传递
// a, b := 1, 2
// E(1, 2) //函数内: [3 4]
// fmt.Println("函数外:", a, b) // 函数外: 1 2
// // slice的内存地址拷贝
// s1 := []int{1, 2, 3, 4}
// F(s1) // 函数内: [5 6 7 8]
// fmt.Println("函数外:", s1) // 函数外: [5 6 7 8]
// // 数据类型的内存地址拷贝
// a1 := 1
// G(&a1)
// fmt.Println("函数外", a1) // 函数外 2
// 匿名函数
// f1 := func() {
// fmt.Println("匿名函数f1")
// }
// f1() // 匿名函数f1
// // 闭包引用外部变量
// n := 1
// f2 := func() int {
// n++
// return n
// }
// fmt.Println("闭包引用外部变量:", f2()) // 闭包引用外部变量: 2
// fmt.Println(n) // 2
// // 闭包作为函数返回值
// f3 := closure(10)
// fmt.Println(f3(1)) // 11
// fmt.Println(f3(2)) // 12
// // defer的调用顺序
// fmt.Print("a ")
// defer fmt.Print("b ")
// defer fmt.Print("c ")
// // a c b
// // 可见defer调用顺序相反
// for i := 0; i < 3; i++ {
// defer fmt.Print(i, " ") // 2 1 0
// }
// defer匿名函数(闭包)
// for i := 0; i < 3; i++ {
// defer func() {
// fmt.Print(i, " ")
// }() // 加()相当于调用匿名函数
// }
// panic
// pA() // Func pA
// pB() // panic: Panic in B
// pC()
// panic/recover
pD() // Func pD
pE() // Recover in pE
pF() // Func pF
}
// // 带参无返回值函数
// func A(a int) {
// fmt.Println(a)
// }
// // 带参有返回值函数——第一种形式,最好声明返回值名称
// func B(a int) (b, c int) {
// b, c = a, a
// return b, c
// }
// // 带参有返回值函数——第二种形式
// func C(a, b int) (int, int) {
// return a, b
// }
// // 可变长度参数,规定必须放在参数列表中的最右边位置
// func D(a ...int) {
// fmt.Println(a) // 可变长度参数相当于一个可变长的数组
// }
// // 值传递
// func E(a ...int) {
// a[0] = 3
// a[1] = 4
// fmt.Println("函数内:", a) // 函数内: [3 4]
// }
// // 内存地址拷贝
// func F(s []int) {
// s[0] = 5
// s[1] = 6
// s[2] = 7
// s[3] = 8
// fmt.Println("函数内:", s) // 函数内: [5 6 7 8]
// }
// // 数据类型的内存地址拷贝
// func G(a *int) {
// *a = 2
// fmt.Println("函数内", *a) // 函数内 2
// }
// 闭包
// func closure(x int) func(int) int {
// fmt.Printf("%p\n", &x) // 0xc0000580a8
// return func(y int) int {
// fmt.Printf("%p\n", &x) // 0xc0000580a8
// return x + y
// }
// }
// func pA() {
// fmt.Println("Func pA")
// }
// func pB() {
// panic("Panic in B")
// }
// func pC() {
// fmt.Println("Func C")
// }
func pD() {
fmt.Println("Func pD")
}
func pE() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Recover in pE")
}
}()
panic("Panic in pE")
}
func pF() {
fmt.Println("Func pF")
}
| true |
6d9f7d7844036e9d3508b1feba90c208ffda5be2
|
Go
|
spiegel-im-spiegel/go-practice
|
/src/join/join.go
|
UTF-8
| 2,221 | 3.15625 | 3 |
[
"CC0-1.0"
] |
permissive
|
[
"CC0-1.0"
] |
permissive
|
package main
import (
"bufio"
"bytes"
"io"
)
//Read content (text data) from buffer
func ContentText(inStream io.Reader) ([]string, error) {
scanner := bufio.NewScanner(inStream)
list := make([]string, 0)
for scanner.Scan() {
list = append(list, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return list, nil
}
//Write content (text data) to buffer
func WriteBuffer1(lines []string) []byte {
//write to byte buffer
content := make([]byte, 0)
recode := "\r\n"
for _, line := range lines {
content = append(content, line...)
content = append(content, recode...)
}
return content
}
//Write content (text data) to buffer
func WriteBuffer1Cap128(lines []string) []byte {
//write to byte buffer
content := make([]byte, 0, 128) //128 bytes capacity
recode := "\r\n"
for _, line := range lines {
content = append(content, line...)
content = append(content, recode...)
}
return content
}
//Write content (text data) to buffer
func WriteBuffer1Cap1K(lines []string) []byte {
//write to byte buffer
content := make([]byte, 0, 1024) //1K bytes capacity
recode := "\r\n"
for _, line := range lines {
content = append(content, line...)
content = append(content, recode...)
}
return content
}
//Write content (text data) to buffer (buffered I/O)
func WriteBuffer2(lines []string) []byte {
//write to byte buffer
content := bytes.NewBuffer(make([]byte, 0))
recode := "\r\n"
for _, line := range lines {
content.WriteString(line)
content.WriteString(recode)
}
return content.Bytes()
}
//Write content (text data) to buffer (buffered I/O)
func WriteBuffer2Cap128(lines []string) []byte {
//write to byte buffer
content := bytes.NewBuffer(make([]byte, 0, 128)) //128 bytes capacity
recode := "\r\n"
for _, line := range lines {
content.WriteString(line)
content.WriteString(recode)
}
return content.Bytes()
}
//Write content (text data) to buffer (buffered I/O)
func WriteBuffer2Cap1K(lines []string) []byte {
//write to byte buffer
content := bytes.NewBuffer(make([]byte, 0, 1024)) //1K bytes capacity
recode := "\r\n"
for _, line := range lines {
content.WriteString(line)
content.WriteString(recode)
}
return content.Bytes()
}
| true |
0c5ba61519c2227da44b271daac2ce304c24d6bb
|
Go
|
buraksekili/spicedb
|
/internal/services/serviceerrors/common.go
|
UTF-8
| 749 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package serviceerrors
import (
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// ReasonReadOnly is the error reason that will show up in ErrorInfo when the service is in
// read-only mode.
ReasonReadOnly = "SERVICE_READ_ONLY"
)
// ErrServiceReadOnly is an extended GRPC error returned when a service is in read-only mode.
var ErrServiceReadOnly = mustMakeStatusReadonly()
func mustMakeStatusReadonly() error {
status, err := status.New(codes.Unavailable, "service read-only").WithDetails(&errdetails.ErrorInfo{
Reason: ReasonReadOnly,
Domain: "authzed.com",
})
if err != nil {
panic("error constructing shared error type")
}
return status.Err()
}
| true |
795d3342a1ea62025c30b0dcc9b4fe32bd68b883
|
Go
|
jcgregorio/inline-form
|
/server.go
|
UTF-8
| 676 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"fmt"
"log"
"net/http"
"os"
)
const template = `
<input type="hidden" name="status" value="%s">
<p>&%s;</p>
<p><input type="submit" value="Toggle"></p>
`
func formHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "text/html")
status := "check"
if r.FormValue("status") == "check" {
status = "cross"
}
fmt.Fprintf(w, template, status, status)
}
func main() {
http.Handle("/", http.FileServer(http.Dir(".")))
http.HandleFunc("/form", formHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
| true |
4c46ba3a81c84c385113a864b6cecc81fe191183
|
Go
|
kohkimakimoto/goparallel
|
/goparallel/writer.go
|
UTF-8
| 1,806 | 3.515625 | 4 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package goparallel
import (
"fmt"
"io"
"strings"
"sync"
)
var printMutex sync.Mutex
type prefixedWriter struct {
Writer io.Writer
Prefix string
newline bool
}
func newPrefixWriter(writer io.Writer, prefix string) *prefixedWriter {
return &prefixedWriter{
Writer: writer,
Prefix: prefix,
newline: true,
}
}
func (w *prefixedWriter) Write(data []byte) (int, error) {
// in order to guarantee writing a single line by the one process. use mutex.
printMutex.Lock()
defer printMutex.Unlock()
dataStr := string(data)
dataStr = strings.Replace(dataStr, "\r\n", "\n", -1)
var hasNewline = false
if dataStr[len(dataStr)-1:] == "\n" {
hasNewline = true
}
if w.Prefix != "" {
if hasNewline {
dataStr = strings.Replace(dataStr, "\n", "\n"+w.Prefix, strings.Count(dataStr, "\n")-1)
} else {
dataStr = strings.Replace(dataStr, "\n", "\n"+w.Prefix, -1) + "\n"
}
fmt.Fprint(w.Writer, w.Prefix+dataStr)
} else {
if hasNewline {
// nothing to do.
} else {
dataStr = dataStr + "\n"
}
fmt.Fprint(w.Writer, dataStr)
}
return len(data), nil
}
//func (w *PrefixedWriter) Write(data []byte) (int, error) {
// dataStr := string(data)
// dataStr = strings.Replace(dataStr, "\r\n", "\n", -1)
//
// if w.newline {
// w.newline = false
// fmt.Fprintf(w.Writer, "%s", w.Prefix)
// }
//
// if strings.Contains(dataStr, "\n") {
// lineCount := strings.Count(dataStr, "\n")
//
// if dataStr[len(dataStr)-1:] == "\n" {
// w.newline = true
// }
//
// if w.newline {
// dataStr = strings.Replace(dataStr, "\n", "\n"+w.Prefix, lineCount-1)
// } else {
// dataStr = strings.Replace(dataStr, "\n", "\n"+w.Prefix, -1)
// }
//
// fmt.Fprintf(w.Writer, "%s", dataStr)
//
// } else {
// fmt.Fprintf(w.Writer, "%s", dataStr)
// }
//
// return len(data), nil
//}
| true |
20a337ec9fcb2fe7fc5dbd7f2c1d232ecd6cecfc
|
Go
|
andir/UthgardCommunityHeraldBackend
|
/main.go
|
UTF-8
| 5,386 | 2.546875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/andir/UthgardCommunityHeraldBackend/timeseries"
radix "github.com/armon/go-radix"
"github.com/gorilla/mux"
)
func parseDump(filename string) map[string]Character {
fh, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
bytes, err := ioutil.ReadAll(fh)
if err != nil {
log.Fatal(err)
}
var characters map[string]Character
err = json.Unmarshal(bytes, &characters)
if err != nil {
log.Fatal(err)
}
return characters
}
// FIXME: replace the global with a context var
var statistics *Statistics
var characterTree *radix.Tree
var guildTree *radix.Tree
func guildInfoEndpoint(wr http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if guild, ok := statistics.ByGuild[vars["guildName"]]; !ok {
return
} else {
wr.Header().Set("Content-Type", "application/json; charset=utf-8")
encoder := json.NewEncoder(wr)
encoder.Encode(guild)
}
}
func totalRPPlayers(wr http.ResponseWriter, req *http.Request) {
wr.Header().Set("Content-Type", "application/json; charset=utf-8")
type TotalRPPlayersJSON struct {
Name string
Guild string
Realm string
Class string
RP uint64
}
players := make([]TotalRPPlayersJSON, len(statistics.SortedByRP))
for i, p := range statistics.SortedByRP {
players[i] = TotalRPPlayersJSON{
Name: p.Name,
Guild: p.Guild,
Realm: p.Realm,
Class: p.Class,
RP: p.Rp,
}
}
encoder := json.NewEncoder(wr)
encoder.Encode(players)
}
func update() {
url := "https://www2.uthgard.net/herald/api/dump"
response, err := http.Get(url)
if err != nil {
log.Println(err)
return
}
var characters map[string]*Character
bytes, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Println(err)
return
}
err = json.Unmarshal(bytes, &characters)
var lastUpdatedInt int64 = 0
for _, value := range characters {
if value.LastUpdated > lastUpdatedInt {
lastUpdatedInt = value.LastUpdated
}
}
go func() {
ctree := radix.New()
for name, character := range characters {
ctree.Insert(strings.ToLower(name), character)
}
characterTree = ctree
}()
stats := LoadCharacters(characters)
go func() {
gtree := radix.New()
for name := range stats.ByGuild {
gtree.Insert(strings.ToLower(name), name)
}
guildTree = gtree
}()
lastUpdated := time.Unix(lastUpdatedInt, 0)
UpdateTimeseries(stats, lastUpdated)
UpdateTopLWRP(stats)
statistics = stats
}
func main() {
go func() {
t := time.NewTicker(30 * time.Minute)
update()
for range t.C {
update()
}
}()
// for guild, data := range statistics.ByGuild {
// TimeSeries{}
// }
r := mux.NewRouter()
endpoints := []struct {
Endpoint string
Func APIFunction
}{
{"/toprp", topRPEndpoint},
{"/topxp", topXPEndpoint},
{"/rp", totalRPEndpoint},
{"/xp", totalXPEndpoint},
{"/toplwxp", topLWRPCharactersEndpoint},
{"/toplwrp", topLWXPCharactersEndpoint},
{"/toplwxp/guilds", topLWRPGuildsEndpoint},
{"/toplwrp/guilds", topLWXPGuildsEndpoint},
{"/toprp/guilds", topRPGuildsEndpoint},
{"/topxp/guilds", topXPGuildsEndpoint},
{"/search/character/{characterName}", searchCharacterEndpoint},
{"/search/guild/{guildName}", searchGuildEndpoint},
{"/character/{characterName}", characterEndpoint},
{"/character/{characterName}/lastwrp", timeSeriesValueSince(timeseries.CharacterRPTimeSeries, "characterName", 7*24*time.Hour)},
{"/character/{characterName}/history/rp", characterRPHistoryEndpoint},
{"/character/{characterName}/history/xp", characterXPHistoryEndpoint},
{"/class/{className}/rp", totalClassRPEndpoint},
{"/class/{className}/xp", totalClassXPEndpoint},
{"/class/{className}/toprp", topClassRPEndpoint},
{"/class/{className}/topxp", topClassXPEndpoint},
{"/class/{className}/history/rp", classRPHistoryEndpoint},
{"/class/{className}/history/xp", classXPHistoryEndpoint},
{"/class/{className}/history/count", classCountHistoryEndpoint},
{"/realm/{realmName}/rp", totalRealmRPEndpoint},
{"/realm/{realmName}/xp", totalRealmXPEndpoint},
{"/realm/{realmName}/toprp", topRealmRPEndpoint},
{"/realm/{realmName}/topxp", topRealmXPEndpoint},
{"/realm/{realmName}/history/rp", realmRPHistoryEndpoint},
{"/realm/{realmName}/history/xp", realmXPHistoryEndpoint},
{"/realm/{realmName}/history/count", realmCountHistoryEndpoint},
{"/guild/{guildName}", guildEndpoint},
{"/guild/{guildName}/rp", totalGuildRPEndpoint},
{"/guild/{guildName}/xp", totalGuildXPEndpoint},
{"/guild/{guildName}/toprp", topGuildRPEndpoint},
{"/guild/{guildName}/topxp", topGuildXPEndpoint},
{"/guild/{guildName}/lastwrp", timeSeriesValueSince(timeseries.GuildRPTimeSeries, "guildName", 7*24*time.Hour)},
{"/guild/{guildName}/history/rp", guildRPHistoryEndpoint},
{"/guild/{guildName}/history/xp", guildXPHistoryEndpoint},
{"/guild/{guildName}/history/count", guildCountHistoryEndpoint},
}
documentation := ""
for _, endpoint := range endpoints {
log.Println(endpoint.Endpoint)
r.Handle(endpoint.Endpoint, apiEndpointWrapper(endpoint.Func))
documentation += endpoint.Endpoint + "\n"
}
r.Handle("/", http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
wr.Header().Set("Content-Type", "text/plain")
wr.Write([]byte(documentation))
}))
http.ListenAndServe("127.0.0.1:8081", r)
}
| true |
3c56df609e7fa087bf7de02d0d5d2d9af4cd9903
|
Go
|
bichonghai/spire
|
/pkg/server/plugin/keymanager/test/test.go
|
UTF-8
| 8,225 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package test
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"crypto/x509"
"math/big"
"testing"
"time"
"github.com/spiffe/spire/pkg/common/x509util"
"github.com/spiffe/spire/proto/server/keymanager"
"github.com/stretchr/testify/suite"
)
var (
ctx = context.Background()
)
type Maker func(t *testing.T) keymanager.Plugin
// the maker function is called. the returned key manager is expected to be
// already configured.
func Run(t *testing.T, maker Maker) {
suite.Run(t, &baseSuite{maker: maker})
}
type baseSuite struct {
suite.Suite
maker Maker
m *keymanager.BuiltIn
}
func (s *baseSuite) SetupTest() {
s.m = keymanager.NewBuiltIn(s.maker(s.T()))
}
func (s *baseSuite) TestGenerateKeyMissingKeyId() {
// missing key id
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyType: keymanager.KeyType_EC_P256,
})
s.Require().Error(err)
s.Require().Nil(resp)
}
func (s *baseSuite) TestGenerateKeyMissingKeyType() {
// missing key type
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
})
s.Require().Error(err)
s.Require().Nil(resp)
}
func (s *baseSuite) TestGenerateKeyECP256() {
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keymanager.KeyType_EC_P256,
})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().NotNil(resp.PublicKey)
s.Require().Equal(resp.PublicKey.Id, "KEY")
s.Require().Equal(resp.PublicKey.Type, keymanager.KeyType_EC_P256)
publicKey, err := x509.ParsePKIXPublicKey(resp.PublicKey.PkixData)
s.Require().NoError(err)
ecdsaPublicKey, ok := publicKey.(*ecdsa.PublicKey)
s.Require().True(ok)
s.Require().Equal(elliptic.P256(), ecdsaPublicKey.Curve)
}
func (s *baseSuite) TestGenerateKeyECP384() {
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keymanager.KeyType_EC_P384,
})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().NotNil(resp.PublicKey)
s.Require().Equal(resp.PublicKey.Id, "KEY")
s.Require().Equal(resp.PublicKey.Type, keymanager.KeyType_EC_P384)
publicKey, err := x509.ParsePKIXPublicKey(resp.PublicKey.PkixData)
s.Require().NoError(err)
ecdsaPublicKey, ok := publicKey.(*ecdsa.PublicKey)
s.Require().True(ok)
s.Require().Equal(elliptic.P384(), ecdsaPublicKey.Curve)
}
func (s *baseSuite) TestGenerateKeyRSA1024() {
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keymanager.KeyType_RSA_1024,
})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().NotNil(resp.PublicKey)
s.Require().Equal(resp.PublicKey.Id, "KEY")
s.Require().Equal(resp.PublicKey.Type, keymanager.KeyType_RSA_1024)
publicKey, err := x509.ParsePKIXPublicKey(resp.PublicKey.PkixData)
s.Require().NoError(err)
rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
s.Require().True(ok)
s.Require().Equal(1024, rsaPublicKey.N.BitLen())
}
func (s *baseSuite) TestGenerateKeyRSA2048() {
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keymanager.KeyType_RSA_2048,
})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().NotNil(resp.PublicKey)
s.Require().Equal(resp.PublicKey.Id, "KEY")
s.Require().Equal(resp.PublicKey.Type, keymanager.KeyType_RSA_2048)
publicKey, err := x509.ParsePKIXPublicKey(resp.PublicKey.PkixData)
s.Require().NoError(err)
rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
s.Require().True(ok)
s.Require().Equal(2048, rsaPublicKey.N.BitLen())
}
func (s *baseSuite) TestGenerateKeyRSA4096() {
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keymanager.KeyType_RSA_4096,
})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().NotNil(resp.PublicKey)
s.Require().Equal(resp.PublicKey.Id, "KEY")
s.Require().Equal(resp.PublicKey.Type, keymanager.KeyType_RSA_4096)
publicKey, err := x509.ParsePKIXPublicKey(resp.PublicKey.PkixData)
s.Require().NoError(err)
rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
s.Require().True(ok)
s.Require().Equal(4096, rsaPublicKey.N.BitLen())
}
func (s *baseSuite) TestGetPublicKeyMissingKeyId() {
resp, err := s.m.GetPublicKey(ctx, &keymanager.GetPublicKeyRequest{})
s.Require().Error(err)
s.Require().Nil(resp)
}
func (s *baseSuite) TestGetPublicKeyNoKey() {
resp, err := s.m.GetPublicKey(ctx, &keymanager.GetPublicKeyRequest{
KeyId: "KEY",
})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().Nil(resp.PublicKey)
}
func (s *baseSuite) TestGetPublicKey() {
resp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keymanager.KeyType_EC_P384,
})
s.Require().NoError(err)
getResp, err := s.m.GetPublicKey(ctx, &keymanager.GetPublicKeyRequest{
KeyId: "KEY",
})
s.Require().NoError(err)
s.Require().NotNil(getResp)
s.Require().Equal(resp.PublicKey, getResp.PublicKey)
}
func (s *baseSuite) TestGetPublicKeysNoKeys() {
resp, err := s.m.GetPublicKeys(ctx, &keymanager.GetPublicKeysRequest{})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().Empty(resp.PublicKeys)
}
func (s *baseSuite) TestGetPublicKeys() {
z, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "Z",
KeyType: keymanager.KeyType_EC_P384,
})
s.Require().NoError(err)
a, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "A",
KeyType: keymanager.KeyType_EC_P384,
})
s.Require().NoError(err)
resp, err := s.m.GetPublicKeys(ctx, &keymanager.GetPublicKeysRequest{})
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().Equal([]*keymanager.PublicKey{a.PublicKey, z.PublicKey}, resp.PublicKeys)
}
func (s *baseSuite) TestSignDataECDSA() {
s.testSignData(keymanager.KeyType_EC_P256, x509.ECDSAWithSHA256)
}
func (s *baseSuite) TestSignDataRSAPKCS1v15() {
s.testSignData(keymanager.KeyType_RSA_1024, x509.SHA256WithRSA)
}
func (s *baseSuite) TestSignDataRSAPSS() {
s.testSignData(keymanager.KeyType_RSA_1024, x509.SHA256WithRSAPSS)
}
func (s *baseSuite) testSignData(keyType keymanager.KeyType, signatureAlgorithm x509.SignatureAlgorithm) {
// create a new key
generateResp, err := s.m.GenerateKey(ctx, &keymanager.GenerateKeyRequest{
KeyId: "KEY",
KeyType: keyType,
})
s.Require().NoError(err)
publicKey, err := x509.ParsePKIXPublicKey(generateResp.PublicKey.PkixData)
s.Require().NoError(err)
// self-sign a certificate with it
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotAfter: time.Now().Add(time.Minute),
SignatureAlgorithm: signatureAlgorithm,
}
// self sign the certificate using the keymanager as a signer
cert, err := x509util.CreateCertificate(ctx, s.m, template, template, "KEY", publicKey)
s.Require().NoError(err)
// verify the signature
roots := x509.NewCertPool()
roots.AddCert(cert)
_, err = cert.Verify(x509.VerifyOptions{
Roots: roots,
})
s.Require().NoError(err)
}
func (s *baseSuite) TestSignDataMissingKeyId() {
resp, err := s.m.SignData(ctx, &keymanager.SignDataRequest{
SignerOpts: &keymanager.SignDataRequest_HashAlgorithm{
HashAlgorithm: keymanager.HashAlgorithm_SHA256,
},
})
s.requireErrorContains(err, "key id is required")
s.Require().Nil(resp)
}
func (s *baseSuite) TestSignDataMissingSignerOpts() {
resp, err := s.m.SignData(ctx, &keymanager.SignDataRequest{
KeyId: "KEY",
})
s.requireErrorContains(err, "signer opts is required")
s.Require().Nil(resp)
}
func (s *baseSuite) TestSignDataMissingHashAlgorithm() {
resp, err := s.m.SignData(ctx, &keymanager.SignDataRequest{
KeyId: "KEY",
SignerOpts: &keymanager.SignDataRequest_HashAlgorithm{},
})
s.requireErrorContains(err, "hash algorithm is required")
s.Require().Nil(resp)
}
func (s *baseSuite) TestSignDataNoKey() {
resp, err := s.m.SignData(ctx, &keymanager.SignDataRequest{
KeyId: "KEY",
SignerOpts: &keymanager.SignDataRequest_HashAlgorithm{
HashAlgorithm: keymanager.HashAlgorithm_SHA256,
},
})
s.requireErrorContains(err, `no such key "KEY"`)
s.Require().Nil(resp)
}
func (s *baseSuite) requireErrorContains(err error, contains string) {
s.Require().Error(err)
s.Require().Contains(err.Error(), contains)
}
| true |
5bba9053c9c64f751bd2866385ac0bc83c851ef1
|
Go
|
ThomasP1988/serverless-cdk-go-graphql
|
/shared/repositories/dynamodb.go
|
UTF-8
| 1,767 | 2.6875 | 3 |
[] |
no_license
|
[] |
no_license
|
package common
import (
"context"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)
func GetOne(client *dynamodb.Client, tableName *string, output interface{}, keys map[string]interface{}) (bool, error) {
var keyCond *expression.KeyConditionBuilder
for k, v := range keys {
if keyCond == nil {
newCond := expression.Key(k).Equal(expression.Value(v))
keyCond = &newCond
} else {
newCond := expression.Key(k).Equal(expression.Value(v))
keyCond.And(newCond)
}
}
expr, err := expression.NewBuilder().WithKeyCondition(*keyCond).Build()
if err != nil {
return false, err
}
input := &dynamodb.QueryInput{
KeyConditionExpression: expr.KeyCondition(),
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
TableName: tableName,
}
queryOutput, err := client.Query(context.TODO(), input)
if err != nil {
return false, err
}
if len(queryOutput.Items) == 0 {
return true, nil
}
err = attributevalue.UnmarshalMap(queryOutput.Items[0], output)
if err != nil {
println("failed to unmarshal Items", err.Error())
return false, err
}
return false, nil
}
func AddOne(client *dynamodb.Client, tableName *string, item interface{}) error {
marshalledItem, err := attributevalue.MarshalMap(item)
if err != nil {
println("dynamodb AddOne, error marshalling item", err.Error())
return err
}
input := &dynamodb.PutItemInput{
Item: marshalledItem,
TableName: tableName,
}
putOutput, err := client.PutItem(context.TODO(), input)
if err != nil {
return err
}
attributevalue.UnmarshalMap(putOutput.Attributes, item)
return nil
}
| true |
e3532cd3e3b0b76168f8e3accdf22b42fecfeccc
|
Go
|
milzero/network
|
/netmodule/tcpsocket.go
|
UTF-8
| 2,267 | 3.40625 | 3 |
[] |
no_license
|
[] |
no_license
|
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 //是否关闭
writeIndex uint //插入缓存索引
}
//newtcpsocket 创建一个tcpsocket
func newtcpsocket(c net.Conn) *tcpsocket {
if c == nil {
//c为nil,抛出异常
panic("c is nil")
}
//初始化结构体
var psocket = new(tcpsocket)
psocket.conn = c
psocket.buffers[0] = new(buffer)
psocket.buffers[1] = new(buffer)
psocket.sendIndex = 0
psocket.notify = make(chan int, 1)
psocket.isclose = 0
psocket.bclose = false
psocket.writeIndex = 1
//启动发送协程
go psocket._dosend()
return psocket
}
func (my *tcpsocket) _dosend() {
writeErr := false
for {
_, ok := <-my.notify
if !ok {
return
}
my.m.Lock()
my.writeIndex = my.sendIndex
my.m.Unlock()
my.sendIndex = (my.sendIndex + 1) % 2
if !writeErr {
var sendSplice = my.buffers[my.sendIndex].Data()
for len(sendSplice) > 0 {
n, err := my.conn.Write(sendSplice)
if err != nil {
writeErr = true
break
}
sendSplice = sendSplice[n:]
}
}
my.buffers[my.sendIndex].Clear()
}
}
//Read 读数据
func (my *tcpsocket) Read(b []byte) (n int, err error) {
return my.conn.Read(b)
}
//WriteBytes 写数据
func (my *tcpsocket) Write(b ...[]byte) {
my.m.Lock()
if my.bclose {
my.m.Unlock()
return
}
dataLen := my.buffers[my.writeIndex].Len()
writeLen := 0
for i := 0; i < len(b); i++ {
writeLen += len(b[i])
my.buffers[my.writeIndex].Append(b[i])
}
if dataLen == 0 && writeLen != 0 {
my.notify <- 0
}
my.m.Unlock()
}
//Close 关闭一个tcpsocket, 释放系统资源
func (my *tcpsocket) Close() {
my.m.Lock()
if my.bclose {
my.m.Unlock()
return
}
my.bclose = true
my.conn.Close()
close(my.notify)
my.m.Unlock()
atomic.StoreUint32(&(my.isclose), 1)
}
//IsClose 判断tcpsocket是否关闭
func (my *tcpsocket) IsClose() bool {
val := atomic.LoadUint32(&(my.isclose))
if val > 0 {
return true
}
return false
}
| true |
df9412a5897a9e59828950ba2ab80c8d13dc5755
|
Go
|
nishanthvasudevan/skipper
|
/filters/builtin/static.go
|
UTF-8
| 2,297 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2015 Zalando 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/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package builtin
import (
"fmt"
"github.com/zalando/skipper/filters"
"net/http"
"path"
)
type static struct {
webRoot, root string
}
// Returns a filter Spec to serve static content from a file system
// location. Marks the request as served.
//
// Filter instances of this specification expect two parameters: a
// request path prefix and a local directory path. When processing a
// request, it clips the prefix from the request path, and appends the
// rest of the path to the directory path. Then, it uses the resulting
// path to serve static content from the file system.
//
// Name: "static".
func NewStatic() filters.Spec { return &static{} }
// "static"
func (spec *static) Name() string { return StaticName }
// Creates instances of the static filter. Expects two parameters: request path
// prefix and file system root.
func (spec *static) CreateFilter(config []interface{}) (filters.Filter, error) {
if len(config) != 2 {
return nil, fmt.Errorf("invalid number of args: %d, expected 1", len(config))
}
webRoot, ok := config[0].(string)
if !ok {
return nil, fmt.Errorf("invalid parameter type, expected string for web root prefix")
}
root, ok := config[1].(string)
if !ok {
return nil, fmt.Errorf("invalid parameter type, expected string for path to root dir")
}
return &static{webRoot, root}, nil
}
// Noop.
func (f *static) Request(filters.FilterContext) {}
// Serves content from the file system and marks the request served.
func (f *static) Response(ctx filters.FilterContext) {
r := ctx.Request()
p := r.URL.Path
if len(p) < len(f.webRoot) {
return
}
ctx.MarkServed()
http.ServeFile(ctx.ResponseWriter(), ctx.Request(), path.Join(f.root, p[len(f.webRoot):]))
}
| true |
c36f9663010cfc5b1ed81e8afec4a73480d8171c
|
Go
|
wuzzapcom/toussaint
|
/backend/app/rest_test.go
|
UTF-8
| 3,383 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package app
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetGame(t *testing.T) {
defer removeDB(t)
srv := httptest.NewServer(http.HandlerFunc(handleGetGames))
resp, err := http.Get(fmt.Sprintf("%s%s", srv.URL, "/games?name="))
assert.Nil(t, err)
assert.Equal(t, http.StatusNotAcceptable, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
assert.Nil(t, err)
assert.Equal(t, 0, len(body))
}
func TestPutRegister1(t *testing.T) {
defer removeDB(t)
registerUser(t, http.StatusCreated)
registerUser(t, http.StatusConflict)
}
func registerUser(t *testing.T, expectedCode int) {
srv := httptest.NewServer(http.HandlerFunc(handlePutUsers))
client := http.Client{}
req, err := http.NewRequest("PUT", fmt.Sprintf("%s%s", srv.URL, "/register?client-id=1&client-type=telegram"), nil)
assert.Nil(t, err)
resp, err := client.Do(req)
assert.Nil(t, err)
assert.Equal(t, expectedCode, resp.StatusCode)
}
func TestPutNotify1(t *testing.T) {
defer removeDB(t)
gameId := "EP9000-CUSA11995_00-MARVELSSPIDERMAN"
putNotify(t, http.StatusNotAcceptable, gameId)
registerUser(t, http.StatusCreated)
putNotify(t, http.StatusCreated, gameId)
}
func putNotify(t *testing.T, expectedStatus int, gameId string) {
srv := httptest.NewServer(http.HandlerFunc(handlePutNotifications))
client := http.Client{}
req, err := http.NewRequest("PUT",
fmt.Sprintf("%s%s",
srv.URL,
fmt.Sprintf("/notify?client-id=1&client-type=telegram&game-id=%s", gameId),
), nil)
assert.Nil(t, err)
resp, err := client.Do(req)
assert.Nil(t, err)
assert.Equal(t, expectedStatus, resp.StatusCode)
}
func TestDeleteNotify1(t *testing.T) {
defer removeDB(t)
srv := httptest.NewServer(http.HandlerFunc(handleDeleteNotifications))
gameId := "EP9000-CUSA11995_00-MARVELSSPIDERMAN"
client := http.Client{}
req, err := http.NewRequest("DELETE",
fmt.Sprintf("%s%s",
srv.URL,
fmt.Sprintf("/notify?client-id=1&client-type=telegram&game-id=%s", gameId),
), nil)
assert.Nil(t, err)
resp, err := client.Do(req)
assert.Nil(t, err)
assert.Equal(t, http.StatusNotAcceptable, resp.StatusCode)
registerUser(t, http.StatusCreated)
putNotify(t, http.StatusCreated, gameId)
resp, err = client.Do(req)
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestGetList(t *testing.T) {
defer removeDB(t)
registerUser(t, http.StatusCreated)
srv := httptest.NewServer(http.HandlerFunc(handleGetList))
resp, err := http.Get(fmt.Sprintf("%s%s", srv.URL, "/list?client-id=1&client-type=telegram&request-type=all"))
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
putNotify(t, http.StatusCreated, "EP9000-CUSA11995_00-MARVELSSPIDERMAN")
putNotify(t, http.StatusCreated, "EP9000-CUSA11995_00-0000000000MSMDLX")
resp, err = http.Get(fmt.Sprintf("%s%s", srv.URL, "/list?client-id=1&client-type=telegram&request-type=all"))
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
data, err := ioutil.ReadAll(resp.Body)
assert.Nil(t, err)
t.Log(string(data))
resp, err = http.Get(fmt.Sprintf("%s%s", srv.URL, "/list?client-id=1&client-type=telegram&request-type=sale"))
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
data, err = ioutil.ReadAll(resp.Body)
assert.Nil(t, err)
t.Log(string(data))
}
| true |
d11b68d5e2b8789d0e3f9c720612aca81c715604
|
Go
|
prestonTao/engine
|
/package.go
|
UTF-8
| 3,294 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package engine
import (
"bytes"
"crypto/rc4"
"encoding/binary"
"errors"
"net"
// "fmt"
)
// var defaultGetPacket GetPacket = RecvPackage
type GetPacket func(cache *[]byte, index *uint32) (packet *Packet, e error)
type GetPacketBytes func(msgID, opt, errcode uint32, cryKey []byte, data *[]byte) *[]byte
type Packet struct {
Opt uint32
MsgID uint32
Size uint32
Errorcode uint32
Data []byte
Crypt_key []byte
Session Session
}
/*
系统默认的消息接收并转化为Packet的方法
一个packet包括包头和包体,保证在接收到包头后两秒钟内接收到包体,否则线程会一直阻塞
因此,引入了超时机制
*/
func RecvPackage(conn net.Conn, packet *Packet) (error, bool) {
// fmt.Println("packet 11111", *index, (*cache))
// if *index < 24 {
// return nil, false
// }
// packet = new(Packet)
cache := make([]byte, 24)
n, err := conn.Read(cache)
// fmt.Println(n, err != nil)
if err != nil || n != 24 {
return err, false
}
packet.Opt = binary.LittleEndian.Uint32((cache)[:4])
packet.Size = binary.LittleEndian.Uint32((cache)[4:8])
packet.MsgID = binary.LittleEndian.Uint32((cache)[8:12])
packet.Errorcode = binary.LittleEndian.Uint32((cache)[12:16])
packet.Crypt_key = (cache)[16:24]
packet.Data = make([]byte, packet.Size-24, packet.Size-24)
n, err = conn.Read(packet.Data)
if err != nil || (uint32(n) != (packet.Size - 24)) {
return err, false
}
if (packet.Opt & 0x00800000) != 0 {
packet.Crypt_key = cry(packet.Crypt_key)
// key := []byte{1, 2, 3, 4, 5, 6, 7}
c, err := rc4.NewCipher(packet.Crypt_key)
if err != nil {
// log.Println("", err)
// Log.Debug("rc4 error: %v", err)
return errors.New("rc4 error " + err.Error()), false
}
// fmt.Println("packet 加解密")
c.XORKeyStream(packet.Data, packet.Data)
}
// fmt.Println("packet data 2", packet.Data)
return nil, true
}
func MarshalPacket(msgID, opt, errcode uint32, cryKey []byte, data *[]byte) *[]byte {
newCryKey := cryKey
if data == nil {
buf := bytes.NewBuffer([]byte{})
binary.Write(buf, binary.LittleEndian, opt)
binary.Write(buf, binary.LittleEndian, uint32(24))
binary.Write(buf, binary.LittleEndian, msgID)
binary.Write(buf, binary.LittleEndian, errcode)
buf.Write(newCryKey)
bs := buf.Bytes()
return &bs
}
bodyBytes := *data
if (opt & 0x00800000) != 0 {
newCryKey = cry(newCryKey)
c, err := rc4.NewCipher(newCryKey)
if err != nil {
// log.Println("rc4 加密 error:", err)
Log.Debug("rc4 加密 error: %v", err)
}
c.XORKeyStream(bodyBytes, bodyBytes)
}
buf := bytes.NewBuffer([]byte{})
binary.Write(buf, binary.LittleEndian, opt)
binary.Write(buf, binary.LittleEndian, uint32(24+len(*data)))
binary.Write(buf, binary.LittleEndian, msgID)
binary.Write(buf, binary.LittleEndian, errcode)
buf.Write(newCryKey)
buf.Write(bodyBytes)
bs := buf.Bytes()
return &bs
}
func cry(in []byte) []byte {
i := 0
tmpBuf := make([]byte, 128)
for i < len(in) {
if i+1 < len(in) {
tmpBuf[i] = in[i+1]
tmpBuf[i+1] = in[i]
} else {
tmpBuf[i] = in[i]
}
i += 2
}
out := make([]byte, len(in))
for i := 0; i < len(in); i++ {
out[i] = tmpBuf[i] & 0x01
out[i] = tmpBuf[i] & 0x0f
out[i] <<= 4
out[i] |= ((tmpBuf[i] & 0xf0) >> 4)
}
return out
}
| true |
d30da3e05d122cec6e7d753b3b211d48daf51955
|
Go
|
odubno/the-go-programming-language
|
/exercism/parallel-letter-frequency/parallel_letter_frequency.go
|
UTF-8
| 1,415 | 4.125 | 4 |
[] |
no_license
|
[] |
no_license
|
package letter
import "sync"
// FreqMap records the frequency of each rune in a given text.
type FreqMap map[rune]int
// Frequency counts the frequency of each rune in a given text and returns this
// data as a FreqMap.
func Frequency(s string) FreqMap {
m := FreqMap{}
for _, r := range s {
m[r]++
}
return m
}
// ConcurrentFrequency uses gorutines to calculate word frequency in text
func ConcurrentFrequency(strings []string) FreqMap {
// wg waits for a group of goroutines to finish
var wg = sync.WaitGroup{}
ch := make(chan FreqMap)
defer close(ch)
// SENDER
// loop over slice of strings, calulate frequency and send results to channel (ch)
// Add() sets the number of goroutines to wait for
wg.Add(len(strings))
for i := 0; i < len(strings); i++ {
data := strings[i]
go func(s string) {
// ch <- sends data to channel
ch <- Frequency(data)
// goroutine has completed
defer wg.Done()
}(data)
}
// RECEIVER
// loop the same amount of times as the sender, request results from sender, copy results to new map
result := FreqMap{}
for i := 0; i < len(strings); i++ {
// <-ch receives data from channel
m := <-ch
// copy results from m
for k, v := range m {
result[k] += v
}
}
// Wait() blocks until all add()ed goroutines are done()
// this ensures that function does not return the result before the goroutine is complete
wg.Wait()
return result
}
| true |
093e72b633e5d2e65a1a83c856079a94fd2ac72a
|
Go
|
htruong/toml
|
/parse.go
|
UTF-8
| 5,995 | 3.34375 | 3 |
[] |
no_license
|
[] |
no_license
|
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 parseRecover(&err)
t := &Tree{}
t.text = text
t.lex = lex(text)
t.parse()
return t, nil
}
// recover is the handler that turns panics into returns from the top level of Parse.
func parseRecover(errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
panic(e)
}
*errp = e.(error)
}
return
}
// next returns the next tok.
func (t *Tree) next() token {
if t.peekCount > 0 {
t.peekCount--
} else {
t.token[0] = t.lex.nextToken()
}
return t.token[t.peekCount]
}
// backup backs the input stream up one tok.
func (t *Tree) backup() {
t.peekCount++
}
// backup2 backs the input stream up two tokens.
// The zeroth token is already there.
func (t *Tree) backup2(t1 token) {
t.token[1] = t1
t.peekCount = 2
}
// backup3 backs the input stream up three tokens
// The zeroth token is already there.
func (t *Tree) backup3(t2, t1 token) { // Reverse order: we're pushing back.
t.token[1] = t1
t.token[2] = t2
t.peekCount = 3
}
// peek returns but does not consume the next tok.
func (t *Tree) peek() token {
if t.peekCount > 0 {
return t.token[t.peekCount-1]
}
t.peekCount = 1
t.token[0] = t.lex.nextToken()
return t.token[0]
}
// nextNonSpace returns the next non-space tok.
func (t *Tree) nextNonSpace() (tok token) {
for {
tok = t.next()
if tok.typ != tokenSpace {
break
}
}
//pd("next %d %s", tok.typ, tok.val)
return tok
}
// peekNonSpace returns but does not consume the next non-space tok.
func (t *Tree) peekNonSpace() (tok token) {
for {
tok = t.next()
if tok.typ != tokenSpace {
break
}
}
t.backup()
return tok
}
// Parsing.
// ErrorContext returns a textual representation of the location of the node in the input text.
func (t *Tree) ErrorContext(n Node) (location, context string) {
pos := int(n.Position())
text := t.text[:pos]
byteNum := strings.LastIndex(text, "\n")
if byteNum == -1 {
byteNum = pos // On first line.
} else {
byteNum++ // After the newline.
byteNum = pos - byteNum
}
lineNum := 1 + strings.Count(text, "\n")
// TODO
//context = n.String()
context = "TODO"
if len(context) > 20 {
context = fmt.Sprintf("%.20s...", context)
}
return fmt.Sprintf("%d:%d", lineNum, byteNum), context
}
// errorf formats the error and terminates processing.
func (t *Tree) errorf(format string, args ...interface{}) {
t.Root = nil
format = fmt.Sprintf("%d: syntax error: %s", t.lex.lineNumber(), format)
panic(fmt.Errorf(format, args...))
}
// error terminates processing.
func (t *Tree) error(err error) {
t.errorf("%s", err)
}
// expect consumes the next token and guarantees it has the required type.
func (t *Tree) expect(expected tokenType, context string) token {
tok := t.nextNonSpace()
if tok.typ != expected {
t.unexpected(tok, context)
}
return tok
}
// expectOneOf consumes the next token and guarantees it has one of the required types.
func (t *Tree) expectOneOf(expected1, expected2 tokenType, context string) token {
tok := t.nextNonSpace()
if tok.typ != expected1 && tok.typ != expected2 {
t.unexpected(tok, context)
}
return tok
}
// unexpected complains about the token and terminates processing.
func (t *Tree) unexpected(tok token, context string) {
t.errorf("unexpected %s in %s", tok, context)
}
func (t *Tree) parse() Node {
t.Root = newList(t.peek().pos)
for t.peek().typ != tokenEOF {
n := t.top()
t.Root.append(n)
}
return nil
}
// key = value
// [keygroup]
func (t *Tree) top() Node {
switch tok := t.peekNonSpace(); tok.typ {
case tokenError:
t.nextNonSpace()
t.errorf("%s", tok.val)
case tokenKeyGroup:
return t.entryGroup()
case tokenKey:
return t.entry()
default:
t.errorf("unexpected %q", tok.val)
return nil
}
return nil
}
// [keygroup]
// ...
func (t *Tree) entryGroup() Node {
token := t.nextNonSpace()
keyGroup := parseKeyGroup(token)
entries := newList(t.peek().pos)
Loop:
for {
switch tok := t.peekNonSpace(); tok.typ {
case tokenKey:
entries.append(t.entry())
default:
break Loop
}
}
return newEntryGroup(token.pos, keyGroup, entries)
}
// "[foo.bar]"
func parseKeyGroup(tok token) *KeyGroupNode {
text := tok.val
name := text[1:len(text)-1]
keys := newList(tok.pos+Pos(1))
for _, v := range strings.Split(name, ".") {
keys.append(newKey(tok.pos+Pos(len(v)), v))
}
return newKeyGroup(tok.pos, keys, text)
}
// key = value
func (t *Tree) entry() Node {
tok := t.nextNonSpace()
key := newKey(tok.pos, tok.val)
//pd("entry %s", tok.val)
t.expect(tokenKeySep, "key seperator")
return newEntry(tok.pos, key, t.value())
}
// value: string, array, ...
func (t *Tree) value() Node {
switch tok := t.nextNonSpace(); tok.typ {
case tokenBool:
return newBool(tok.pos, tok.val == "true")
case tokenNumber:
v, err := newNumber(tok.pos, tok.val)
if err != nil { t.error(err) }
return v
case tokenString:
//pd("str %d %s", tok.typ, tok.val)
v, err := strconv.Unquote(tok.val)
if err != nil { t.error(err) }
return newString(tok.pos, v, tok.val)
case tokenDatetime:
v, err := time.Parse(time.RFC3339, tok.val)
if err != nil { t.error(err) }
return newDatetime(tok.pos, v)
case tokenArrayStart:
return t.array()
default:
t.errorf("unexpected %q in value", tok.val)
return nil
}
return nil
}
// [1, 2]
func (t *Tree) array() Node {
pos := t.peek().pos
array := newList(pos)
Loop:
for {
switch tok := t.peekNonSpace(); tok.typ {
case tokenArrayEnd:
t.nextNonSpace()
break Loop
default:
//pd("array %s", tok.val)
node := t.value()
if t.peekNonSpace().typ != tokenArrayEnd {
t.expect(tokenArraySep, "array")
}
array.append(node)
}
}
return newArray(pos, array)
}
| true |
07e289fddb2527d89edcb0d9bab916cec43292cf
|
Go
|
one2nc/ts2fa
|
/auth/exports.go
|
UTF-8
| 1,069 | 2.75 | 3 |
[] |
no_license
|
[] |
no_license
|
package auth
import (
"fmt"
"log"
"net/http"
)
func Validate(f http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lock.RLock()
var startup bool
if store == nil {
startup = true
lock.RUnlock()
if err := initStore(); err != nil {
http.Error(w, fmt.Sprintf("init-store-error: %+v", err), http.StatusInternalServerError)
return
}
}
if !startup {
defer lock.RUnlock()
}
if email, token, ok := r.BasicAuth(); !ok || !store.isValid(email, token) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
f.ServeHTTP(w, r)
})
}
// Fetch data from pritunl and update userStore
func RefreshHandler(w http.ResponseWriter, r *http.Request) {
data, err := fetchPritunlData()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
store.update(data)
if _, err := w.Write([]byte(`{"success": true}`)); err != nil {
log.Printf("response-write-error: %+v", err)
}
}
| true |
05cb3b333f57f95c84bd4ece69f0f24f50eceff5
|
Go
|
firmanJS/phonebook-service
|
/mocks/testcases/get_phonebook.go
|
UTF-8
| 3,677 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package testcases
import (
"database/sql"
"github.com/sapawarga/phonebook-service/helper"
"github.com/sapawarga/phonebook-service/model"
)
// ResponseFromUsecase ...
type ResponseFromUsecase struct {
Result *model.PhoneBookWithMeta
Error error
}
// ResponseGetList ...
type ResponseGetList struct {
Result []*model.PhoneBookResponse
Error error
}
// ResponseGetMetadata ...
type ResponseGetMetadata struct {
Result int64
Error error
}
// GetPhoneBook ...
type GetPhoneBook struct {
Description string
UsecaseParams model.ParamsPhoneBook
GetListParams model.GetListRequest
GetMetaDataParams model.GetListRequest
MockUsecase ResponseFromUsecase
MockGetList ResponseGetList
MockGetMetadata ResponseGetMetadata
}
// GetPhoneBookData ...
var GetPhoneBookData = []GetPhoneBook{
{
Description: "success get phone book",
UsecaseParams: model.ParamsPhoneBook{
Search: helper.SetPointerString("kantor"),
Limit: helper.SetPointerInt64(10),
Page: helper.SetPointerInt64(1),
},
GetListParams: model.GetListRequest{
Search: helper.SetPointerString("kantor"),
Limit: helper.SetPointerInt64(10),
Offset: helper.SetPointerInt64(0),
},
GetMetaDataParams: model.GetListRequest{
Search: helper.SetPointerString("kantor"),
Limit: helper.SetPointerInt64(10),
Offset: helper.SetPointerInt64(0),
},
MockUsecase: ResponseFromUsecase{
Result: &model.PhoneBookWithMeta{
PhoneBooks: []*model.Phonebook{
{
ID: 1,
Name: "kantor",
PhoneNumbers: `[{"phone_number": "022123"}]`,
Description: "kantor cabang MCD",
},
{
ID: 2,
Name: "kantor",
PhoneNumbers: `[{"phone_number": "423443"}]`,
Description: "kantor makanan",
},
},
Page: 1,
Total: 2,
},
Error: nil,
},
MockGetMetadata: ResponseGetMetadata{
Result: 2,
Error: nil,
},
MockGetList: ResponseGetList{
Result: []*model.PhoneBookResponse{
{
ID: 1,
Name: sql.NullString{String: "kantor", Valid: true},
PhoneNumbers: sql.NullString{String: `[{"type":"phone", "phone_number":"+62812312131"]`, Valid: true},
Description: sql.NullString{String: "kantor cabang MCD", Valid: true},
},
{
ID: 2,
Name: sql.NullString{String: "kantor", Valid: true},
PhoneNumbers: sql.NullString{String: `[{"type":"phone", "phone_number":"+62812312131"]`, Valid: true},
Description: sql.NullString{String: "kantor makanan", Valid: true},
},
},
Error: nil,
},
}, {
Description: "success when get nil data",
UsecaseParams: model.ParamsPhoneBook{
Search: helper.SetPointerString("random name"),
Limit: helper.SetPointerInt64(10),
Page: helper.SetPointerInt64(1),
},
GetListParams: model.GetListRequest{
Search: helper.SetPointerString("random name"),
Limit: helper.SetPointerInt64(10),
Offset: helper.SetPointerInt64(0),
},
GetMetaDataParams: model.GetListRequest{
Search: helper.SetPointerString("random name"),
Limit: helper.SetPointerInt64(10),
Offset: helper.SetPointerInt64(0),
},
MockUsecase: ResponseFromUsecase{
Result: &model.PhoneBookWithMeta{
PhoneBooks: nil,
Page: 1,
Total: 0,
},
Error: nil,
},
MockGetList: ResponseGetList{
Result: nil,
Error: nil,
},
MockGetMetadata: ResponseGetMetadata{
Result: 0,
Error: nil,
},
},
}
// ListPhonebookDescription :
func ListPhonebookDescription() []string {
var arr = []string{}
for _, data := range GetPhoneBookData {
arr = append(arr, data.Description)
}
return arr
}
| true |
962beada98f995c9436074f1e167c5a50c53bd74
|
Go
|
hwartig/adventofcode
|
/2015/01/main.go
|
UTF-8
| 630 | 3.0625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"strconv"
"../../aoc"
)
func Part1(input string) string {
result := 0
for _, c := range input {
if c == '(' {
result += 1
} else if c == ')' {
result -= 1
} else {
// log.Fatal("found unknown rune", c)
}
}
return strconv.Itoa(result)
}
func Part2(input string) string {
result := 0
for i, c := range input {
if c == '(' {
result += 1
} else if c == ')' {
result -= 1
}
if result == -1 {
return strconv.Itoa(i + 1)
}
}
return strconv.Itoa(-1)
}
func main() {
fmt.Println(Part1(aoc.ReadInput())) // 138
fmt.Println(Part2(aoc.ReadInput())) // 1771
}
| true |
913ad640c0bc472cc04ce79a2e8340365f1b314e
|
Go
|
karlmcguire/gocme
|
/examples/Gfmt/main.go
|
UTF-8
| 1,017 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
"os/exec"
"strings"
"github.com/karlmcguire/gocme"
)
func main() {
// Get the id of the current window.
id, err := gocme.GetId()
if err != nil {
panic(err)
}
// Get the absolute filepath of the current window.
filename, err := gocme.GetFilename(id)
if err != nil {
panic(err)
}
// Get the contents of the current window.
body, err := gocme.GetBody(id)
if err != nil {
panic(err)
}
// Run "gofmt" on the file.
rawfix, err := exec.Command("gofmt", filename).Output()
if err != nil {
// Gofmt returned an error.
if e, ok := err.(*exec.ExitError); ok {
// Output the gofmt error to Errors window.
fmt.Print(string(e.Stderr))
}
} else {
fix := string(rawfix)
// Check if new contents is any different than present contents.
if strings.Compare(body, fix) != 0 {
// Set the body of the current window to the new contents.
e := gocme.SetBody(id, fix)
if e != nil {
panic(e)
}
} else {
// Already formatted, all done.
}
}
}
| true |
bc61b7974fa7620714ff57203d120d0427726e2e
|
Go
|
BestNathan/go-template
|
/internal/pkg/database/entity.go
|
UTF-8
| 989 | 2.515625 | 3 |
[] |
no_license
|
[] |
no_license
|
package database
import (
"time"
"github.com/bwmarrin/snowflake"
"github.com/google/uuid"
)
var snowflakeNode *snowflake.Node
func init() {
n, err := snowflake.NewNode(1)
if err != nil {
panic(err)
}
snowflakeNode = n
}
type UUIDPrimaryKey struct {
ID uuid.UUID `gorm:"comment:UUID主键;primarykey;type:uuid;default:uuid_generate_v4()" `
}
func NewUUIDPrimaryKey() *UUIDPrimaryKey {
return &UUIDPrimaryKey{ID: uuid.New()}
}
type AutoIncrementPrimaryKey struct {
ID int `gorm:"comment:自增主键;primarykey;autoIncrement"`
}
type SnowflakePrimaryKey struct {
ID *snowflake.ID `gorm:"comment:雪花主键;primarykey"`
}
func NewSnowFlakePrimaryKey() SnowflakePrimaryKey {
id := snowflakeNode.Generate()
return SnowflakePrimaryKey{ID: &id}
}
type Entity struct {
CreatedTime time.Time `gorm:"comment:创建时间;index;autoCreateTime" `
UpdatedTime time.Time `gorm:"comment:更新时间;autoUpdateTime" `
IsDeleted bool `gorm:"comment:删除标记" `
}
| true |
0bb2754cffbb483d66705a9ee2e568baf01f2010
|
Go
|
SouLxBurN/go-url-shortener
|
/client/mongo.go
|
UTF-8
| 802 | 2.8125 | 3 |
[] |
no_license
|
[] |
no_license
|
package client
import (
"context"
"sync"
"time"
"url-shortener/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var mongoClient *mongo.Client
var mongoError error
var mongoInit sync.Once
// GetMongoClient Returns a reference to a mongo.Client
func GetMongoClient() (*mongo.Client, error) {
mongoInit.Do(func() {
mongoConfig := config.GetMongoConfig()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOptions := options.Client().ApplyURI(mongoConfig.ConnectionString)
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
mongoError = err
}
err = client.Ping(ctx, nil)
if err != nil {
mongoError = err
}
mongoClient = client
})
return mongoClient, mongoError
}
| true |
1dde49742e74fbc94c690b506863f0d03ced97fc
|
Go
|
AndrewRussellHayes/fgo
|
/command/init.go
|
UTF-8
| 4,883 | 2.609375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// command/init.go
//
// Copyright (c) 2016-2017 Junpei Kawamoto
//
// This software is released under the MIT License.
//
// http://opensource.org/licenses/mit-license.php
//
package command
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/deiwin/interact"
"github.com/jkawamoto/fgo/fgo"
colorable "github.com/mattn/go-colorable"
"github.com/ttacon/chalk"
"github.com/urfave/cli"
"github.com/tcnksm/go-gitconfig"
)
// InitOpt defines options for cmdInit.
type InitOpt struct {
// Configuration
Config Config
// GitHub user name.
UserName string
// GitHub repository name.
Repository string
// Description of the target application.
Description string
}
// Generater is an interface provides Generate method.
type Generater interface {
Generate() ([]byte, error)
}
// CmdInit parses options and run cmdInit.
func CmdInit(c *cli.Context) error {
opt := InitOpt{
Config: Config{
Package: c.GlobalString(PackageFlag),
Homebrew: c.GlobalString(HomebrewFlag),
},
UserName: c.Args().First(),
Repository: c.Args().Get(1),
Description: c.String("desc"),
}
return cmdInit(&opt)
}
// cmdInit defines init command action.
func cmdInit(opt *InitOpt) (err error) {
stdout := colorable.NewColorableStdout()
// Check user name.
if opt.UserName == "" {
fmt.Fprintf(stdout, "Checking git configuration to get the user name: ")
opt.UserName, err = gitconfig.GithubUser()
if err != nil {
fmt.Fprintf(stdout, chalk.Red.Color("Cannot find user name (%v)"), err.Error())
return cli.NewExitError("", 1)
}
fmt.Fprintln(stdout, chalk.Yellow.Color(opt.UserName))
}
// Prepare directories.
fmt.Fprintf(stdout, "Preparing the directory to store a brew formula: ")
if err = prepareDirectory(opt.Config.Homebrew); err != nil {
fmt.Fprintf(stdout, chalk.Red.Color("failed (%v)"), err.Error())
return cli.NewExitError("", 2)
}
fmt.Fprintln(stdout, chalk.Green.Color("done"))
// Check Makefile doesn't exist and create it.
actor := interact.NewActor(os.Stdin, stdout)
createMakefile := true
if _, exist := os.Stat("Makefile"); exist == nil {
createMakefile, err = actor.Confirm("Makefile already exists. Would you like to overwrite it?", interact.ConfirmDefaultToNo)
if err != nil {
fmt.Fprintf(stdout, chalk.Red.Color("failed (%v)"), err.Error())
return cli.NewExitError("", 3)
}
}
if createMakefile {
fmt.Fprintf(stdout, "Creating Makefile: ")
err = createResource("Makefile", &fgo.Makefile{
Dest: opt.Config.Package,
UserName: opt.UserName,
})
if err != nil {
fmt.Fprintf(stdout, chalk.Yellow.Color("skipped (%s)\n"), err.Error())
} else {
fmt.Fprintln(stdout, chalk.Green.Color("done"))
}
} else {
fmt.Fprintln(stdout, "Creating Makefile:", chalk.Yellow.Color("skipped"))
}
// Check brew rb file doesn't exist and create it.
if opt.Repository == "" {
fmt.Fprintf(stdout, "Checking git configuration to get the repository name: ")
opt.Repository, err = gitconfig.Repository()
if err != nil {
fmt.Fprintf(stdout, chalk.Red.Color("skipped (%s).\n"), err.Error())
fmt.Fprintln(stdout, chalk.Yellow.Color("You must re-run init command after setting a remote repository"))
}
fmt.Fprintln(stdout, chalk.Yellow.Color(opt.Repository))
}
if opt.Repository != "" {
tmpfile := filepath.Join(opt.Config.Homebrew, fmt.Sprintf("%s.rb.template", opt.Repository))
createTemplate := true
if _, exist := os.Stat(tmpfile); exist == nil {
createTemplate, err = actor.Confirm("brew formula template already exists. Would you like to overwrite it?", interact.ConfirmDefaultToNo)
if err != nil {
fmt.Fprintf(stdout, chalk.Red.Color("failed (%v)"), err.Error())
return cli.NewExitError("", 3)
}
}
if createTemplate {
fmt.Fprintf(stdout, "Creating brew formula template: ")
err = createResource(tmpfile, &fgo.FormulaTemplate{
Package: opt.Repository,
UserName: opt.UserName,
Description: opt.Description,
})
if err != nil {
fmt.Fprintf(stdout, chalk.Yellow.Color("skipped (%s).\n"), err.Error())
} else {
fmt.Fprintln(stdout, chalk.Green.Color("done"))
}
} else {
fmt.Fprintln(stdout, "Creating brew formula template:", chalk.Yellow.Color("skipped"))
}
}
return
}
// prepareDirectory creates a directory if necessary.
func prepareDirectory(path string) error {
if info, exist := os.Stat(path); exist == nil && !info.IsDir() {
return fmt.Errorf("cannot make directory %s", path)
} else if err := os.MkdirAll(path, 0755); err != nil {
return fmt.Errorf("cannot make directory %s (%s)", path, err.Error())
}
return nil
}
// createResource creates a resource from a given generator and stores it to
// a given path.
func createResource(path string, data Generater) (err error) {
buf, err := data.Generate()
if err != nil {
return
}
return ioutil.WriteFile(path, buf, 0644)
}
| true |
c66d55f6bb298ae7d8a782eab834cfb4ba98660d
|
Go
|
InoAyaka/programmingGo
|
/Verification/p027/default.go
|
UTF-8
| 253 | 3.25 | 3 |
[] |
no_license
|
[] |
no_license
|
//p.27 defaultの判定位置は本当に最後かデバッグで見てみる
package main
import "fmt"
func main() {
x := 0
switch {
case x > 0:
fmt.Println("case1")
default:
fmt.Println("defalut")
case x < 0:
fmt.Println("case2")
}
}
| true |
6306634df94890c9b8898008b71c1da34fecc8a4
|
Go
|
beevik/hexdump
|
/dump/dump.go
|
UTF-8
| 361 | 2.671875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/beevik/hexdump"
)
func main() {
flag.Parse()
args := flag.Args()
if len(args) == 0 {
fmt.Printf("Usage: dump [file]\n")
os.Exit(0)
}
b, err := ioutil.ReadFile(args[0])
if err != nil {
fmt.Printf("ERROR: %v\n", err)
return
}
hexdump.Dump(b, hexdump.FormatGo, os.Stdout)
}
| true |
f7249af3adfa8550caf2fd084b4a4c028e841a8c
|
Go
|
hskimim/go_tutorial
|
/tutorial/accounts/accounts.go
|
UTF-8
| 629 | 3.71875 | 4 |
[] |
no_license
|
[] |
no_license
|
package accounts
import (
"errors"
)
type bankAccount struct {
owner string
balance int
}
var errNoMoney = errors.New("you can't withdraw money more than you have")
func NewAccount(name string) *bankAccount {
accounts := bankAccount{owner: name, balance: 0}
return &accounts
}
func (b *bankAccount) Deposit(money int) {
b.balance += money
}
func (b bankAccount) ShowBalance() int {
return b.balance
}
func (b *bankAccount) Withdraw(money int) error {
if b.balance-money < 0 {
return errNoMoney
}
b.balance -= money
return nil
}
func (b bankAccount) String() string {
return "this is about bank account"
}
| true |
152090b6ab391b782c9e768c8ee3c73d3afe79f1
|
Go
|
kcwebapply/svad
|
/adapter/proxyHttpAdapter.go
|
UTF-8
| 981 | 2.546875 | 3 |
[] |
no_license
|
[] |
no_license
|
package adapter
import (
"fmt"
"net/http"
"github.com/kcwebapply/svad/infrastructure/http_wrapper"
)
func ProxyRequest(requestURL string, contentType string, request *http.Request) (*http.Response, error) {
return doRequest(requestURL, contentType, request)
}
func doRequest(requestURL string, contentType string, request *http.Request) (*http.Response, error) {
switch request.Method {
case http.MethodGet:
response, err := http_wrapper.GetRequest(requestURL, request)
return response, err
case http.MethodPost:
response, err := http_wrapper.PostRequest(requestURL, contentType, request)
return response, err
case http.MethodPut:
response, err := http_wrapper.PutRequest(requestURL, contentType, request)
return response, err
case http.MethodDelete:
response, err := http_wrapper.DeleteRequest(requestURL, contentType, request)
return response, err
}
return nil, fmt.Errorf("request method %s doesn't supporeted on this server", request.Method)
}
| true |
c3061cafdab69f7849803f7e8eb4a4c0e4279148
|
Go
|
ruiHut/go_practice
|
/src/basicGrammer/struct.go
|
UTF-8
| 716 | 3.96875 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
// 结构体 既可以关联方法 也可以 内置字段
// 简单实例 针对中文的演示级聊天机器人
type simpleCN struct {
name string
talk string
}
// 声明使用方式
var simple1 = simpleCN{"hello", "world"} // 可以省略字段名 顺序需要一致 零值为nil
var simple2 simpleCN
func main() {
// new 函数分配一个指针, 此处的p的类型为 *person &对象 代表其指针
simple3 := new(simpleCN)
simple2.name = "zhouwang"
simple2.talk = "hello i am zhouwang!"
fmt.Println(simple1)
fmt.Println(&simple2)
testStruct(simple3)
fmt.Println(simple3)
}
func testStruct(p *simpleCN) {
p.name = "zhouwang"
p.talk = "hello i am good boy"
}
| true |
52661fb22cdb01ffcdac1bdb30e2aee0b8433762
|
Go
|
softstake/ton-dice-web-fetcher
|
/fetcher/utils.go
|
UTF-8
| 1,480 | 2.75 | 3 |
[] |
no_license
|
[] |
no_license
|
package fetcher
import (
"context"
"encoding/base64"
"fmt"
store "github.com/tonradar/ton-dice-web-server/proto"
"io/ioutil"
"log"
"regexp"
"strconv"
)
func parseOutMessage(m string) (*GameResult, error) {
log.Println("Start parsing an outgoing message...")
msg, err := base64.StdEncoding.DecodeString(m)
if err != nil {
log.Printf("Мessage decode failed: %v\n", err)
return nil, err
}
log.Printf("Decoded message - '%s'", string(msg))
if len(msg) > 0 {
r, _ := regexp.Compile(`TONBET.IO - \[#(\d+)] Your number is (\d+), all numbers greater than (\d+) have won.`)
matches := r.FindStringSubmatch(string(msg))
if len(matches) > 0 {
randomRoll, _ := strconv.Atoi(matches[3])
betID, _ := strconv.Atoi(matches[1])
return &GameResult{Id: betID, RandomRoll: randomRoll}, nil
}
log.Println("Message does not match expected pattern")
} else {
log.Println("Message is empty")
}
return nil, fmt.Errorf("message is not valid")
}
func isBetResolved(s store.BetsClient, id int32) (*store.IsBetResolvedResponse, error) {
isBetResolvedReq := &store.IsBetResolvedRequest{
Id: id,
}
resp, err := s.IsBetResolved(context.Background(), isBetResolvedReq)
if err != nil {
return nil, err
}
return resp, nil
}
func GetSavedTrxLt(fn string) (int, error) {
data, err := ioutil.ReadFile(fn)
if err != nil {
return 0, err
}
savedTrxLt, err := strconv.Atoi(string(data))
if err != nil {
return 0, err
}
return savedTrxLt, nil
}
| true |
7672b652e4f361124035fb32a0c4fc9fe7829a03
|
Go
|
Zhanatmod/golang
|
/learning/7-2.go
|
UTF-8
| 254 | 3.25 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func half(x int) (int, bool) {
if x % 2 == 0 {
return 1, true
} else {
return 0, false
}
}
func main() {
fmt.Println("Введите число: ")
var input int
fmt.Scanf("%d", &input)
fmt.Println(half(input))
}
| true |
3c9894fe3f0ba94e0bedf1c70a9c11d734b4f7f9
|
Go
|
gongzili456/-algorithm015
|
/Week_01/42.接雨水.go
|
UTF-8
| 573 | 2.796875 | 3 |
[] |
no_license
|
[] |
no_license
|
package leetcode
/*
* @lc app=leetcode.cn id=42 lang=golang
*
* [42] 接雨水
*/
// @lc code=start
func trap(height []int) int {
s := []int{0}
current, ans := 0, 0
for current < len(height) {
for len(s) > 0 && height[current] > height[s[len(s)-1]] {
top := s[len(s)-1]
s = s[:len(s)-1]
if len(s) <= 0 {
break
}
distance := current - top - 1
h := s[len(s)-1]
if height[current] < h {
h = height[current]
}
h -= height[top]
ans += distance * h
}
current++
s = append(s, current)
}
return ans
}
// @lc code=end
| true |
48a04acf47c47a93f8e32f73d3174da2bdf24d30
|
Go
|
ash2k/stager
|
/stage.go
|
UTF-8
| 659 | 3.390625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package stager
import (
"context"
)
type Stage interface {
// Go starts f in a new goroutine attached to the Stage.
// Stage context is passed to f as an argument. f should stop when context signals done.
// If f returns a non-nil error, the stager starts performing shutdown.
Go(f func(context.Context) error)
}
type stage struct {
ctx context.Context
cancelStage context.CancelFunc
cancelStagerRun context.CancelFunc
errChan chan error
n int
}
func (s *stage) Go(f func(context.Context) error) {
s.n++
go func() {
err := f(s.ctx)
if err != nil {
s.cancelStagerRun()
}
s.errChan <- err
}()
}
| true |
82945ec24ef083c0d831ae398ea360eaf286bb26
|
Go
|
jnovikov/urlshorter
|
/keystorage/storage_test.go
|
UTF-8
| 805 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package keystorage
import (
"testing"
)
func TestStorage_NotExists(t *testing.T) {
m := NewMockStorage()
res := m.Get("not_found")
if res != nil {
t.Error("Failed to check what key not found")
}
}
func TestStorageWrapper_Exists(t *testing.T) {
m := NewMockStorage()
w := StorageWrapper{m}
if w.Exists("not_found") {
t.Error("Failed to check what key not found")
}
}
func TestStorageWrapper_GetString(t *testing.T) {
m := NewMockStorage()
w := StorageWrapper{m}
w.Set("asd", "asd")
if w.GetString("asd") != "asd" {
t.Error("Failed to get string by key")
}
}
func TestStorageWrapper_GetBadString(t *testing.T) {
m := NewMockStorage()
w := StorageWrapper{m}
w.Set("asd", 1)
res := w.GetString("asd")
if res != "" {
t.Error("Failed to get empty string then type error")
}
}
| true |
c607cb0ea1d1613287a8012b6cc6802c0cb1b1f0
|
Go
|
abachir/webserver1
|
/webserver.go
|
UTF-8
| 1,117 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"flag"
"log"
"net/http"
)
var p = flag.String("p", "8080", "TCP port")
var d = flag.String("d", "/", "target directory")
func main() {
flag.Parse()
http.Handle("/", http.FileServer(http.Dir(*d)))
//http.HandleFunc("/view", makeHandler(getFileHandler))
log.Fatal(http.ListenAndServe("localhost:"+*p, nil))
}
/*
func fetchFile(title string) ([]byte, error) {
filename := title + ".txt"
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return b, nil
}
func getFileHandler(w http.ResponseWriter, req *http.Request, title string) {
title = *d
substr := title[1:]
b, err := fetchFile(substr)
if err != nil {
fmt.Fprint(w, "could not fetch file. File not found ", http.StatusNotFound)
return
}
s := string(b)
fmt.Fprint(w, s)
return
}
func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
title := req.URL.Path
fn(w, req, title)
}
}
//func hello(w http.ResponseWriter, req *http.Request) {
// fmt.Fprintf(w, "%v", "hello, Gopher! and welcome")
//}
*/
| true |
6c826e1ce85f5e452cf79d3f6733eb4ffc54b7d5
|
Go
|
Cepave/open-falcon-backend
|
/modules/alarm/g/redis.go
|
UTF-8
| 630 | 2.640625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package g
import (
"github.com/garyburd/redigo/redis"
log "github.com/sirupsen/logrus"
"time"
)
var RedisConnPool *redis.Pool
func InitRedisConnPool() {
redisConfig := Config().Redis
RedisConnPool = &redis.Pool{
MaxIdle: redisConfig.MaxIdle,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", redisConfig.Addr)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: PingRedis,
}
}
func PingRedis(c redis.Conn, t time.Time) error {
_, err := c.Do("ping")
if err != nil {
log.Println("[ERROR] ping redis fail", err)
}
return err
}
| true |
e901ee023e039abb5b78c1f1e9cd75bce4dd6e04
|
Go
|
intercom/intercom-go
|
/conversation_api_test.go
|
UTF-8
| 5,215 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package intercom
import (
"io/ioutil"
"testing"
)
func TestConversationFind(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations/147", fixtureFilename: "fixtures/conversation.json"}
api := ConversationAPI{httpClient: &http}
convo, _ := api.find("147")
if convo.ID != "147" {
t.Errorf("Conversation not retrieved, %s", convo.ID)
}
if convo.TagList == nil || convo.TagList.Tags[0].ID != "12345" {
t.Errorf("Conversation tags not retrieved, %s", convo.ID)
}
if convo.ConversationMessage.ID != "537e564f316c33104c010020" {
t.Errorf("Conversation ID not retrieved, %s", convo.ConversationMessage.ID)
}
if convo.ConversationMessage.URL != "/the/page/url.html" {
t.Errorf("Conversation URL not retrieved, %s", convo.ConversationMessage.URL)
}
}
func TestConversationRead(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations/147", fixtureFilename: "fixtures/conversation.json"}
http.testFunc = func(t *testing.T, readRequest interface{}) {
req := readRequest.(conversationReadRequest)
if req.Read != true {
t.Errorf("read was not marked true")
}
}
api := ConversationAPI{httpClient: &http}
convo, err := api.read("147")
if err != nil {
t.Errorf("%v", err)
}
if convo.ID != "147" {
t.Errorf("Conversation not retrieved, %s", convo.ID)
}
}
func TestConversationReply(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations/147/reply", fixtureFilename: "fixtures/conversation.json"}
http.testFunc = func(t *testing.T, replyRequest interface{}) {
reply := replyRequest.(*Reply)
if reply.ReplyType != CONVERSATION_NOTE.String() {
t.Errorf("Reply was not note")
}
}
api := ConversationAPI{httpClient: &http}
convo, err := api.reply("147", &Reply{ReplyType: CONVERSATION_NOTE.String(), AdminID: "123"})
if err != nil {
t.Errorf("%v", err)
}
if convo.ID != "147" {
t.Errorf("Conversation not retrieved, %s", convo.ID)
}
}
func TestConversationReplyWithAttachment(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations/147/reply", fixtureFilename: "fixtures/conversation.json"}
http.testFunc = func(t *testing.T, replyRequest interface{}) {
reply := replyRequest.(*Reply)
if reply.ReplyType != CONVERSATION_COMMENT.String() {
t.Errorf("Reply was not comment")
}
}
api := ConversationAPI{httpClient: &http}
convo, err := api.reply("147", &Reply{ReplyType: CONVERSATION_COMMENT.String(), AdminID: "123", AttachmentURLs: []string{"http://www.example.com/attachment.jpg"}})
if err != nil {
t.Errorf("%v", err)
}
if convo.ID != "147" {
t.Errorf("Conversation not retrieved, %s", convo.ID)
}
}
func TestConversationListAll(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations", fixtureFilename: "fixtures/conversations.json"}
api := ConversationAPI{httpClient: &http}
convos, _ := api.list(ConversationListParams{})
if convos.Conversations[0].ID != "147" {
t.Errorf("Conversation not retrieved")
}
if convos.Conversations[0].User.ID != "536e564f316c83104c000020" {
t.Errorf("Conversation user not retrieved")
}
if convos.Conversations[0].ConversationMessage.Author.ID != "25" {
t.Errorf("Conversation Message Author not retrieved")
}
if convos.Conversations[0].ConversationParts.Parts[0].CreatedAt != 1400857494 {
t.Errorf("Conversation Part CreatedAt not retrieved")
}
if convos.Conversations[0].TagList != nil {
t.Errorf("Conversation Tags should be nil")
}
}
func TestConversationListUserUnread(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations", fixtureFilename: "fixtures/conversations.json"}
http.testFunc = func(t *testing.T, queryParams interface{}) {
ps := queryParams.(ConversationListParams)
if *ps.Unread != true {
t.Errorf("Expect unread parameter, got %v", *ps.Unread)
}
}
api := ConversationAPI{httpClient: &http}
api.list(ConversationListParams{Unread: Bool(true)})
}
func TestConversationListAdminOpen(t *testing.T) {
http := TestConversationHTTPClient{t: t, expectedURI: "/conversations", fixtureFilename: "fixtures/conversations.json"}
http.testFunc = func(t *testing.T, queryParams interface{}) {
ps := queryParams.(ConversationListParams)
if *ps.Open != true {
t.Errorf("Expect open parameter, got %v", *ps.Unread)
}
}
api := ConversationAPI{httpClient: &http}
api.list(ConversationListParams{Open: Bool(true)})
}
type TestConversationHTTPClient struct {
TestHTTPClient
t *testing.T
testFunc func(t *testing.T, queryParams interface{})
fixtureFilename string
expectedURI string
lastQueryParams interface{}
}
func (t *TestConversationHTTPClient) Get(uri string, queryParams interface{}) ([]byte, error) {
if t.testFunc != nil {
t.testFunc(t.t, queryParams)
}
if t.expectedURI != uri {
t.t.Errorf("Wrong endpoint called")
}
return ioutil.ReadFile(t.fixtureFilename)
}
func (t *TestConversationHTTPClient) Post(uri string, dataObject interface{}) ([]byte, error) {
if t.testFunc != nil {
t.testFunc(t.t, dataObject)
}
if t.expectedURI != uri {
t.t.Errorf("Wrong endpoint called")
}
return ioutil.ReadFile(t.fixtureFilename)
}
| true |
8b90a2a0c651b6cb537a3cd263ec88be6121c767
|
Go
|
colinz2023/play
|
/leetcode/stack&queue/0347_Top_K_Frequent_Elements/main.go
|
UTF-8
| 550 | 3.140625 | 3 |
[] |
no_license
|
[] |
no_license
|
//package _347_Top_K_Frequent_Elements
package main
import (
"fmt"
)
func topKFrequent(nums []int, k int) []int {
freq := make(map[int]int)
bucket := make([][]int, len(nums)+1)
res := make([]int, 0)
for _, n := range nums {
freq[n]++
}
for k, v := range freq {
bucket[v] = append(bucket[v], k)
}
for i := len(nums); i >= 0; i-- {
for _, v := range bucket[i] {
res = append(res, v)
if len(res) == k {
return res
}
}
}
return res
}
func main() {
s1 := []int{1, 1, 1, 2, 2, 3}
fmt.Println(topKFrequent(s1, 2))
}
| true |
0b7c1a7c0f645585a5b93ced191ba8a42056f3d5
|
Go
|
godcong/wego-manager
|
/controller/errors.go
|
UTF-8
| 421 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package controller
import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"net/http"
)
// CodeMessage ...
type CodeMessage struct {
Code int `json:"code" example:"-1"`
Message string `json:"message" example:"status bad request"`
}
// Error ...
func Error(ctx *gin.Context, err error) {
log.Error(err)
ctx.JSON(http.StatusBadRequest, CodeMessage{
Code: -1,
Message: err.Error(),
})
}
| true |
b29f6476adea19b08e1c4089c5eb4984930b074c
|
Go
|
DuoSoftware/v6engine-deps
|
/github.com/signintech/gopdf/embedfont_obj.go
|
UTF-8
| 896 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package gopdf
import (
"bytes"
"io/ioutil"
"strconv"
)
type EmbedFontObj struct{
buffer bytes.Buffer
Data string
zfontpath string
font IFont
}
func (me *EmbedFontObj) Init(funcGetRoot func()(*GoPdf)) {
}
func (me *EmbedFontObj) Build() {
b, err := ioutil.ReadFile(me.zfontpath)
if err != nil {
return
}
me.buffer.WriteString("<</Length "+ strconv.Itoa(len(b)) +"\n")
me.buffer.WriteString("/Filter /FlateDecode\n")
me.buffer.WriteString("/Length1 "+strconv.Itoa(me.font.GetOriginalsize())+"\n")
me.buffer.WriteString(">>\n")
me.buffer.WriteString("stream\n")
me.buffer.Write(b)
me.buffer.WriteString("\nendstream\n")
}
func (me *EmbedFontObj) GetType() string {
return "EmbedFont"
}
func (me *EmbedFontObj) GetObjBuff() *bytes.Buffer {
return &(me.buffer)
}
func (me *EmbedFontObj) SetFont(font IFont,zfontpath string){
me.font = font
me.zfontpath = zfontpath
}
| true |
84cd37072dc6fe658b55bf162b7d4012c310e11b
|
Go
|
715047274/devfarm
|
/cmd/core/cli/cmds/devfarm/runall/command_test.go
|
UTF-8
| 2,720 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
package runall
import (
"github.com/dena/devfarm/cmd/core/cli"
"github.com/dena/devfarm/cmd/core/cli/planfile"
"github.com/dena/devfarm/cmd/core/platforms"
"github.com/dena/devfarm/cmd/core/testutil"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
)
func TestCommand(t *testing.T) {
stderrSpy := testutil.NewWriteCloserSpy(nil)
procInout := cli.AnyProcInout()
procInout.Stderr = stderrSpy
planfilePath, planfileErr := anyPlanfilePath()
if planfileErr != nil {
t.Error(planfileErr)
return
}
args := []string{"--dry-run", planfilePath}
_ = command(args, procInout)
// FIXME: dry-run but failed now... dry-run should succeed if the given data aws correct.
t.Log(stderrSpy.Captured.String())
}
func anyPlanfilePath() (string, error) {
iosPlan, iosErr := anyIOSPlan()
if iosErr != nil {
return "", iosErr
}
androidPlan, androidErr := anyAndroidPlan()
if androidErr != nil {
return "", androidErr
}
plans := planfile.NewPlanfile(iosPlan, androidPlan)
dirname, dirErr := ioutil.TempDir(os.TempDir(), "fixture")
if dirErr != nil {
return "", dirErr
}
filename := filepath.Join(dirname, "planfile.yml")
file, openErr := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
if openErr != nil {
return "", openErr
}
defer file.Close()
if writeErr := planfile.Encode(*plans, file); writeErr != nil {
return "", writeErr
}
return filename, nil
}
func anyAndroidPlan() (platforms.EitherPlan, error) {
dirname, dirErr := ioutil.TempDir(os.TempDir(), "fixture")
if dirErr != nil {
return platforms.EitherPlan{}, dirErr
}
filename := filepath.Join(dirname, "devfarm-example.apk")
file, openErr := os.OpenFile(filename, os.O_CREATE, 0644)
if openErr != nil {
return platforms.EitherPlan{}, openErr
}
defer file.Close()
return platforms.NewAndroidPlan(
"any-platform",
"any-group",
platforms.AndroidDevice{
DeviceName: "apple iphone xs",
OSVersion: "12.0",
},
platforms.APKPathOnLocal(filename),
"com.example.app.id",
platforms.AndroidIntentExtras{},
10*time.Second,
"test-2",
).Either(), nil
}
func anyIOSPlan() (platforms.EitherPlan, error) {
dirname, dirErr := ioutil.TempDir(os.TempDir(), "fixture")
if dirErr != nil {
return platforms.EitherPlan{}, dirErr
}
filename := filepath.Join(dirname, "devfarm-example.ipa")
file, openErr := os.OpenFile(filename, os.O_CREATE, 0644)
if openErr != nil {
return platforms.EitherPlan{}, openErr
}
defer file.Close()
return platforms.NewIOSPlan(
"any-platform",
"any-group",
platforms.IOSDevice{
DeviceName: "apple iphone xs",
OSVersion: "12.0",
},
platforms.IPAPathOnLocal(filename),
platforms.IOSArgs{},
10*time.Second,
"test-1",
).Either(), nil
}
| true |
3cdf8362bbc6010d90c50fcf6da6864ac79119f4
|
Go
|
toshinarin/go-googlesheets
|
/example/main.go
|
UTF-8
| 2,697 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"github.com/toshinarin/go-googlesheets"
"golang.org/x/oauth2/google"
"google.golang.org/api/sheets/v4"
)
func newService(configJsonPath, credentialsFileName string) (*sheets.Service, error) {
b, err := ioutil.ReadFile(configJsonPath)
if err != nil {
return nil, err
}
// If modifying these scopes, delete your previously saved credentials
// at ~/.google_oauth_credentials/{credentialsFileName}
config, err := google.ConfigFromJSON([]byte(b), "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
return nil, fmt.Errorf("Unable to parse client secret file to config: %v", err)
}
srv, err := googlesheets.New(config, credentialsFileName)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve Sheets Client %v", err)
}
return srv, nil
}
func importSpreadSheet(srv *sheets.Service, spreadsheetId, spreadsheetRange string) error {
resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, spreadsheetRange).Do()
if err != nil {
return fmt.Errorf("Unable to retrieve data from sheet. %v", err)
}
for i, row := range resp.Values {
fmt.Printf("row[%d]; %s\n", i, row)
}
return nil
}
func exportToSpreadSheet(srv *sheets.Service, spreadsheetId, spreadsheetRange string, rows [][]interface{}) error {
valueRange := sheets.ValueRange{}
for _, r := range rows {
valueRange.Values = append(valueRange.Values, r)
}
clearReq := sheets.ClearValuesRequest{}
clearResp, err := srv.Spreadsheets.Values.Clear(spreadsheetId, spreadsheetRange, &clearReq).Do()
if err != nil {
return fmt.Errorf("failed to clear sheet. error: %v", err)
}
log.Printf("clear response: %v", clearResp)
resp, err := srv.Spreadsheets.Values.Update(spreadsheetId, spreadsheetRange, &valueRange).ValueInputOption("RAW").Do()
if err != nil {
return fmt.Errorf("failed to update sheet. error: %v", err)
}
log.Printf("update response: %v", resp)
return nil
}
func main() {
mode := flag.String("mode", "import", "import or export")
spreadSheetID := flag.String("id", "", "google spread sheet id")
flag.Parse()
if *spreadSheetID == "" {
log.Fatal("option -id: please set spread sheet id")
}
srv, err := newService("client_secret.json", "googlesheets-example.json")
if err != nil {
log.Fatal(err)
}
if *mode == "import" {
if err := importSpreadSheet(srv, *spreadSheetID, "A1:B"); err != nil {
log.Fatal(err)
}
} else if *mode == "export" {
rows := [][]interface{}{[]interface{}{"a1", "b1"}, []interface{}{"a2", "b2"}}
if err := exportToSpreadSheet(srv, *spreadSheetID, "A1:B", rows); err != nil {
log.Fatal(err)
}
} else {
log.Fatal("option -mode: please set import or export")
}
}
| true |
c6c2d2032811449a7e1d687f5447d3d3fbb31c76
|
Go
|
OneiroXL/GO
|
/Study/Channel/example/expamle1/main.go
|
UTF-8
| 895 | 3.609375 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
type Result struct{
Key int
Value int
}
var (
chanNum chan int = make(chan int,16)
chanRes chan Result = make(chan Result,500)
chanExit chan<- bool = make(chan bool,8)
)
func Write(){
for i := 1; i <= 500; i++ {
chanNum<-i
}
close(chanNum)
}
func AddUp(){
for i := 0; i < 500; i++ {
num,ok := <-chanNum
if(!ok){
chanExit<-true
break;
}
var res int
for i := 1; i <= num; i++ {
res = res + i
}
//放入结果管道
var r Result = Result{}
r.Key = num;
r.Value = res;
chanRes <- r;
}
}
func ShowRes(){
for r := range chanRes {
fmt.Printf("结果为:res[%v] = %v \n",r.Key,r.Value)
}
}
func main() {
go Write()
for i := 0; i < cap(chanExit); i++ {
go AddUp()
}
for {
if(len(chanExit)== cap(chanExit)){
close(chanRes)
close(chanExit)
break
}
}
ShowRes()
fmt.Println("执行完毕!!!")
}
| true |
2c99459704374b69711f889a57745415d51c59cd
|
Go
|
noiseunion/bassnectar
|
/pkg/server/instance.go
|
UTF-8
| 442 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package server
import (
"net/http"
"github.com/go-chi/chi"
"github.com/sirupsen/logrus"
)
// Instance is an "instance" of our server
type Instance struct {
Logger *logrus.Logger
httpServer *http.Server
router *chi.Mux
routeBuilder *RouteBuilder
}
// RenderRoutes will render our RouteBuilder routes into the server instance.
func (instance *Instance) RenderRoutes() {
instance.routeBuilder.RenderRoutes(instance)
}
| true |
38e3c477cdf856e9d5b221975b4ed0394bcb0ec2
|
Go
|
Syati/gotodo
|
/cmd/seed/main.go
|
UTF-8
| 1,327 | 2.578125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"database/sql"
"fmt"
"github.com/Syati/gotodo/config"
_ "github.com/go-sql-driver/mysql"
"github.com/jessevdk/go-flags"
"io/ioutil"
"log"
"os"
"path/filepath"
)
var opts struct {
Path string `long:"path" description:"A name" required:"true"`
}
func main() {
parser := flags.NewParser(&opts, flags.Default)
if _, err := parser.Parse(); err != nil {
log.Fatal(err)
}
c := config.GetConfig()
con, err := sql.Open("mysql", c.GetString("db.dsn"))
if err != nil {
parser.WriteHelp(os.Stdout)
os.Exit(1)
}
defer con.Close()
for _, path := range dirwalk(opts.Path) {
b, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
result, err := con.Exec(string(b))
if err != nil {
log.Fatal(err)
}
num, _ := result.RowsAffected()
fmt.Printf("Affected row: %d\n", num)
}
}
func dirwalk(seedDir string) []string {
seedDir, _ = filepath.Abs(seedDir)
files, err := ioutil.ReadDir(seedDir)
if err != nil {
panic(err)
}
var paths []string
for _, file := range files {
if file.IsDir() && file.Name() == config.GetConfig().GetString("APP_ENV") {
paths = append(paths, dirwalk(filepath.Join(seedDir, file.Name()))...)
continue
}
path := filepath.Join(seedDir, file.Name())
fmt.Println(path)
paths = append(paths, path)
}
return paths
}
| true |
4a3bb74fab842811f8325bbd77891a60d0ef82af
|
Go
|
robertDurst/buzz
|
/cmd/root.go
|
UTF-8
| 679 | 2.953125 | 3 |
[] |
no_license
|
[] |
no_license
|
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "buzz",
Short: "A CLI tool to generate USD volume data for a given Stellar account.",
Long: `A CLI tool to generate USD volume data for a given Stellar account. This will be used by Lightyear partners and the Lightyear partnership team to measure volume for particular accounts of interest.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(`Probably not what you are looking for!
Consider running the --help command.
To infinity and beyond!`)
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
| true |
efdc45e2954c7c03cf0d781428115f8986481f2c
|
Go
|
proidiot/pullcord
|
/trigger/trigger.go
|
UTF-8
| 794 | 2.671875 | 3 |
[] |
no_license
|
[] |
no_license
|
package trigger
import (
// "github.com/stuphlabs/pullcord"
)
// TriggerHandler is an abstract interface describing a system which provides
// triggers that can be called based on certain events (like a service being
// detected as down, an amount of time passing without a service being
// accessed, etc.). For the moment, the only trigger mechanism provided is a
// simple string being passed in, and although additional trigger mechanisms
// could be added later, it is not yet clear that others would be necessary.
//
// TriggerString is a function that provides a trigger mechanism based on an
// arbitrary string. A minimal amount of additional structure could be achieved
// through the use of serialization format like JSON.
type TriggerHandler interface {
Trigger() (err error)
}
| true |
2545dec5ec7d6bfe34205ee33c9b25c6e8e856a5
|
Go
|
gemunulk/go-notebook
|
/testing/testing_test.go
|
UTF-8
| 332 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
"testing"
)
// 1. Filename ends with = filename_test.go
// Start method name with Test = Test_methodname()
// CMD = go test -run Test_Something -v
func Test_Something(t *testing.T) {
// test stuff here...
Something(t)
}
func Something(t *testing.T) {
// test stuff here...
fmt.Println("GRRR")
}
| true |
be0e76e545ce591687102df782452fb3724368db
|
Go
|
quintans/goSQL
|
/db/named_parameter_utils.go
|
UTF-8
| 3,257 | 3.171875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
[
"BSD-2-Clause"
] |
permissive
|
package db
import (
tk "github.com/quintans/toolkit"
coll "github.com/quintans/toolkit/collections"
"github.com/quintans/toolkit/ext"
"unicode"
)
// Set of characters that qualify as parameter separators,
// indicating that a parameter name in a SQL String has ended.
const PARAMETER_SEPARATORS = `"':&,;()|=+-*%/\<>^`
//Set of characters that qualify as comment or quotes starting characters.
var START_SKIP = []string{"'", "\"", "--", "/*"}
// Set of characters that at are the corresponding comment or quotes ending characters.
var STOP_SKIP = []string{"'", "\"", "\n", "*/"}
// Parse the SQL statement and locate any placeholders or named parameters.
// Named parameters are substituted for a native placeholder.
//
// param statement: the SQL statement
// return: the parsed statement, represented as ParsedSql instance
func ParseSqlStatement(statement string) *ParsedSql {
namedParameters := coll.NewHashSet()
parsedSql := NewParsedSql(statement)
length := len(statement)
for i := 0; i < length; i++ {
c := statement[i]
if c == ':' || c == '&' {
j := i + 1
if j < length && statement[j] == ':' && c == ':' {
// Postgres-style "::" casting operator - to be skipped.
i = i + 2
continue
}
for j < length && !isParameterSeparator(rune(statement[j])) {
j++
}
if (j - i) > 1 {
parameter := ext.Str(statement[i+1 : j])
if !namedParameters.Contains(parameter) {
namedParameters.Add(parameter)
}
parsedSql.AddNamedParameter(parameter.String(), i, j)
}
i = j - 1
}
}
return parsedSql
}
// Determine whether a parameter name ends at the current position,
// that is, whether the given character qualifies as a separator.
func isParameterSeparator(c rune) bool {
if unicode.IsSpace(c) {
return true
}
for _, ps := range PARAMETER_SEPARATORS {
if c == ps {
return true
}
}
return false
}
// Parse the SQL statement and locate any placeholders or named parameters.
// Named parameters are substituted for a '?' placeholder
//
// param parsedSql
// the parsed represenation of the SQL statement
// param paramSource
// the source for named parameters
// return the SQL statement with substituted parameters
// see #parseSqlStatement
func SubstituteNamedParameters(parsedSql *ParsedSql, translator Translator) string {
originalSql := parsedSql.String()
actualSql := tk.NewStrBuffer()
paramNames := parsedSql.Names
lastIndex := 0
for i, v := range paramNames {
indexes := parsedSql.Indexes[i]
startIndex := indexes[0]
endIndex := indexes[1]
actualSql.Add(originalSql[lastIndex:startIndex])
actualSql.Add(translator.GetPlaceholder(i, v))
lastIndex = endIndex
}
actualSql.Add(originalSql[lastIndex:])
return actualSql.String()
}
// converts SQL with named parameters to the specialized Database placeholders
//
// param sql
// The SQL to be converted
// param params
// The named parameters and it's values
// @return The {@link RawSql} with the result
func ToRawSql(sql string, translator Translator) *RawSql {
rawSql := new(RawSql)
rawSql.OriSql = sql
parsedSql := ParseSqlStatement(sql)
rawSql.Names = parsedSql.Names
rawSql.Sql = SubstituteNamedParameters(parsedSql, translator)
return rawSql
}
| true |
090037ff08df52ad9a205a52a3360ec378bcaf18
|
Go
|
lovego/pool
|
/pool_test.go
|
UTF-8
| 5,671 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package pool
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/url"
"strings"
"sync"
"time"
)
func ExamplePool() {
var pool, err = New(func(ctx context.Context) (io.Closer, error) {
return net.Dial("tcp", "baidu.com:80")
}, func(ctx context.Context, r *Resource) bool {
if time.Since(r.IdleAt) < time.Minute {
return true
}
// check if r.Resource() is usable, may be by a ping or noop operation
return true
}, 5, 2)
if err != nil {
panic(err)
}
// this can also be doing concurrently
for i := 0; i < 10; i++ {
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
// get a connection
resource, err := pool.Get(ctx)
if err != nil {
panic(err)
}
// do some work with the connection ...
conn := resource.Resource().(net.Conn)
conn.Write(nil)
// put the connection back
if err := pool.Put(resource); err != nil {
panic(err)
}
}
// Output:
}
var testPool, _ = New(openTestResource, nil, 10, 5)
type testResource struct {
}
func (tr testResource) Close() error {
return nil
}
func openTestResource(ctx context.Context) (io.Closer, error) {
return testResource{}, nil
}
func ExamplePool_TestSerially() {
r1, err := testPool.Get(context.Background())
checkResultAndPrintPoolStatus(r1, err, testPool)
r2, err := testPool.Get(context.Background())
checkResultAndPrintPoolStatus(r2, err, testPool)
if err := testPool.Put(r1); err != nil {
fmt.Println(err)
} else {
printPoolStatus(testPool)
}
if err := testPool.Put(r2); err != nil {
fmt.Println(err)
} else {
printPoolStatus(testPool)
}
r3, err := testPool.Get(context.Background())
checkResultAndPrintPoolStatus(r3, err, testPool)
r4, err := testPool.Get(context.Background())
checkResultAndPrintPoolStatus(r4, err, testPool)
if err := testPool.Close(r3); err != nil {
fmt.Println(err)
} else {
printPoolStatus(testPool)
}
if err := testPool.Close(r4); err != nil {
fmt.Println(err)
} else {
printPoolStatus(testPool)
}
// Output:
// 1 1 0
// 2 2 0
// 2 1 1
// 2 0 2
// 2 1 1
// 2 2 0
// 1 1 0
// 0 0 0
}
func ExamplePool_TestConcurrently() {
var resources = make(chan *Resource, testPool.maxOpen)
var wg sync.WaitGroup
for i := 0; i < testPool.maxOpen; i++ {
wg.Add(1)
go func() {
r, err := testPool.Get(context.Background())
checkResult(r, err)
resources <- r
wg.Done()
}()
}
wg.Wait()
printPoolStatus(testPool)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Millisecond)
fmt.Println(testPool.Get(ctx))
printPoolStatus(testPool)
go func() {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Millisecond)
r, err := testPool.Get(ctx)
checkResult(r, err)
}()
time.Sleep(time.Millisecond) // wait for the previous goroutine to be ready.
for i := 0; i < testPool.maxOpen; i++ {
wg.Add(1)
go func(i int) {
var fn func(*Resource) error
if i < 6 || rand.Int()%2 == 0 {
fn = testPool.Put
} else {
fn = testPool.Close
}
if err := fn(<-resources); err != nil {
fmt.Println(err)
}
wg.Done()
}(i)
}
wg.Wait()
printPoolStatus(testPool)
// Output:
// 10 10 0
// <nil> pool: get resource timeout.
// 10 10 0
// 6 1 5
}
func checkResultAndPrintPoolStatus(r *Resource, err error, p *Pool) {
checkResult(r, err)
printPoolStatus(p)
}
func checkResult(r *Resource, err error) {
if r == nil || r.Resource() == nil || !r.OpenedAt.Before(time.Now()) || err != nil {
fmt.Println(r, err)
}
}
func printPoolStatus(p *Pool) {
fmt.Println(p.opened, len(p.busy), len(p.idle))
}
func ExampleNew_Test() {
p, err := New(openTestResource, nil, 0, -1)
fmt.Println(p, err)
p, _ = New(openTestResource, nil, 10, 11)
fmt.Println(p.maxOpen, p.maxIdle)
// Output:
// <nil> pool: invalid maxOpen: 0
// 10 10
}
func ExampleNew2_Test() {
p, _ := New2(openTestResource, nil, nil)
fmt.Println(p.maxOpen, p.maxIdle)
p, _ = New2(openTestResource, nil, url.Values{
"maxOpen": []string{"5"},
"maxIdle": []string{"2"},
})
fmt.Println(p.maxOpen, p.maxIdle)
// Output:
// 10 1
// 5 2
}
func ExamplePool_Get_TestError() {
p, _ := New(func(ctx context.Context) (io.Closer, error) {
return testResource{}, errors.New("error")
}, nil, 10, 5)
fmt.Println(p.Get(context.Background()))
printPoolStatus(p)
// Output:
// <nil> error
// 0 0 0
}
func ExamplePool_Get_TestCloseIfShould() {
var usable = true
p, _ := New(openTestResource, func(context.Context, *Resource) bool {
return usable
}, 1, 1)
testCloseIfShould(p)
usable = false
testCloseIfShould(p)
// Output:
// true
// false
}
func testCloseIfShould(p *Pool) {
r1, err := p.Get(context.Background())
checkResult(r1, err)
if err := p.Put(r1); err != nil {
fmt.Println(err)
}
r2, err := p.Get(context.Background())
checkResult(r2, err)
if err := p.Put(r2); err != nil {
fmt.Println(err)
}
fmt.Println(r1 == r2)
}
func ExamplePool_TestErrorResource() {
fmt.Println(testPool.Put(nil))
fmt.Println(testPool.Put(&Resource{Closer: testResource{}}))
fmt.Println(testPool.Close(nil))
fmt.Println(testPool.Close(&Resource{}))
// Output:
// pool: the resource is not got from this pool or already been put back or closed.
// pool: the resource is not got from this pool or already been put back or closed.
// pool: the resource is not got from this pool or already been put back or closed.
// pool: the resource is not got from this pool or already been put back or closed.
}
func ExamplePool_TestDecrease() {
defer func() {
fmt.Println(strings.HasSuffix(recover().(string), " pool: opened(-1) < idle(0)"))
}()
p, _ := New(openTestResource, nil, 1, 1)
p.decrease()
// Output: true
}
| true |
bd4eff7fb1a180ba22266e4a010758f0acfe37ee
|
Go
|
calmh/mole
|
/cmd/mole/readpass_windows.go
|
UTF-8
| 253 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"bufio"
"fmt"
"os"
)
func readpass(prompt string) string {
warnln(msgPasswordVisible)
fmt.Printf(prompt)
bf := bufio.NewReader(os.Stdin)
line, _, err := bf.ReadLine()
if err != nil {
return ""
}
return string(line)
}
| true |
451ed226e23d043a36e12d53311e015d2aa77fc0
|
Go
|
OlegSchwann/rpsarena-ru-backend
|
/game_server/types/rotate.go
|
UTF-8
| 1,156 | 2.78125 | 3 |
[] |
no_license
|
[] |
no_license
|
package types
// User1 видит карту так же, как и сервер. User0 видит всё отражённым,
// что бы небыло различий между пользователями на фронте.
// приходяшие структуры надо разворачивать сразу после парсинга, 1 раз.
func (a *AttemptGoToCell) Rotate() {
a.From = 41 - a.From
a.To = 41 - a.To
return
}
func (rw *ReassignWeapons) Rotate() {
rw.CharacterPosition = 41 - rw.CharacterPosition
return
}
func (dm *DownloadMap) Rotate() {
for i := 0; i < 21; i++ {
dm[i], dm[41-i] = dm[41-i], dm[i]
}
return
}
func (mc *MoveCharacter) Rotate() {
mc.From = 41 - mc.From
mc.To = 41 - mc.To
return
}
func (a *Attack) Rotate() {
a.Winner.Coordinates = 41 - a.Winner.Coordinates
a.Loser.Coordinates = 41 - a.Loser.Coordinates
return
}
func (aw *AddWeapon) Rotate() {
aw.Coordinates = 41 - aw.Coordinates
return
}
func (wcr *WeaponChangeRequest) Rotate() {
wcr.CharacterPosition = 41 - wcr.CharacterPosition
return
}
func (g *GameOver) Rotate() {
g.From = 41 - g.From
g.To = 41 - g.To
return
}
| true |
3e0e278c67b0e74321d747e09d89c23fe2dc62d5
|
Go
|
bereadyfor/acl-checker
|
/dial.go
|
UTF-8
| 999 | 2.875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"io/ioutil"
"log"
"net"
"os"
yaml "gopkg.in/yaml.v2"
)
type Config struct {
Type string
Dst string
Port string
Notify string
}
type Configs struct {
Cfgs []Config `tasks`
}
func main() {
confFile, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Panicf("Read config. err #%v ", err)
}
var configs Configs
err = yaml.Unmarshal(confFile, &configs)
if err != nil {
log.Panicf("Parse config. err #%v ", err)
}
for _, config := range configs.Cfgs {
log.Println(config)
if config.Type == "ip" {
health, err := checkPort("tcp", config.Dst, config.Port)
log.Println(health, err)
}
}
}
func checkPort(protocol string, ip string, port string) (bool, error) {
conn, err := net.Dial(protocol, ip+":"+port)
if err != nil {
return false, err
} else {
defer conn.Close()
return true, nil
}
}
func checkPing() {
/* TODO implement */
}
func checkDNSLookup() {
/* TODO implement */
}
func notify() {
/* TODO implement */
}
| true |
3475525fcf0c9378e63753fb036d019aca7fe1d5
|
Go
|
shzawa/gowebprog
|
/scratch/ch03/03-hello-world-handler-func-mux/server.go
|
UTF-8
| 622 | 3.84375 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"net/http"
)
// ハンドラ関数 メソッドServeHTTPと同じシグネチャを持つ関数
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
func world(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "World!")
}
func main() {
server := http.Server{
Addr: ":8080",
}
http.HandleFunc("/hello", hello)
// ↑ のHandleFuncが内部で行っていることを具体化したもの
worldHandler := http.HandlerFunc(world) // HandlerFuncは、メソッドではなく型
http.Handle("/world", &worldHandler)
server.ListenAndServe()
}
| true |
3a36befa8810332effced11fce1ea2dfe3bca40c
|
Go
|
cjj1024/Image-Spider
|
/get_roame/go/spider.go
|
UTF-8
| 3,428 | 2.640625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/wonderivan/logger"
)
func init() {
logger.SetLogger("log.json")
}
func GetImageNameAndUrl(url string) []Image {
doc, err := goquery.NewDocument(url)
if err != nil {
logger.Error("Get Document %s error!", url)
logger.Error(err)
}
var images []Image
doc.Find(".fbi").Each(func(i int, selection *goquery.Selection) {
tmp := selection.Find("a")
url_tmp, _ := tmp.Attr("href")
url = getImageUrl(url_tmp)
name, _ := tmp.Find("img").Attr("src")
name_slice := strings.Split(name, "/")
name = name_slice[len(name_slice)-1]
name = strings.Split(name, ".")[0]
url = url + name + ".jpg"
images = append(images, Image{name, url})
logger.Info("Add a image url, name: %s, url: %s", name, url)
})
return images
}
// Cookie
//
// cmd JekxvVbCarH6ZH16F2C8dQnWu4eJaQgn
// Hm_lpvt_633fe378147652d6cb58809821524bec 1552975739
// Hm_lvt_633fe378147652d6cb58809821524bec 1552552570,1552556853,1552891683,1552975723
// uid 255971
// upw a0663602d3f2ce2f0194a855af395d19
// cmd="Y8ZLdpKLvWmN3F3lf1I0tPge2Uc6WraXQ",
// Hm_lpvt_633fe378147652d6cb58809821524bec = "1552975739",
// Hm_lvt_633fe378147652d6cb58809821524bec="1552552570,1552556853,1552891683,1552975723",
// uid="255971",
// upw="a0663602d3f2ce2f0194a855af395d19"
var cookie string = `cmd=JekxvVbCarH6ZH16F2C8dQnWu4eJaQgn;Hm_lpvt_633fe378147652d6cb58809821524bec=1552975739;Hm_lvt_633fe378147652d6cb58809821524bec=1552552570,1552556853,1552891683,1552975723;uid=255971;upw=a0663602d3f2ce2f0194a855af395d19`
func getImageUrl(url string) string {
// url = "https://www.roame.net/" + url
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
logger.Error("Set Request %s Error!", url)
logger.Error(err)
}
req.Header.Set("Cookie", cookie)
req.Header.Add("Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763")
resp, err := client.Do(req)
if err != nil {
logger.Error("Get Response Error!")
logger.Error(err)
}
html_byte, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
html := string(html_byte)
// fmt.Println(html)
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
logger.Error("Get Document %s Error!", url)
logger.Error(err)
return ""
}
img_url, _ := doc.Find("#darlnks").Find("a").Eq(1).Attr("href")
return img_url
}
func GetImage(url string) []byte {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
logger.Error("Set Request Error!")
logger.Error(err)
}
req.Header.Set("Cookie", cookie)
req.Header.Add("Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763")
resp, err := client.Do(req)
if err != nil {
logger.Error("Downlaod Image Error!")
logger.Error(err)
}
defer resp.Body.Close()
pix, err := ioutil.ReadAll(resp.Body)
logger.Info("Download Image %s Succussfully!", url)
return pix
}
func SaveImage(image []byte, name string) {
name = name + ".jpg"
out, err := os.Create(name)
if err != nil {
logger.Error("Create Image File Error!")
logger.Error(err)
}
defer out.Close()
io.Copy(out, bytes.NewReader(image))
logger.Info("Save Image %s Suffessfully!", name)
}
| true |
28cfe8e24ac5f59862ea50b80a6a5a88f9c7a041
|
Go
|
gbulmer/svgo
|
/adapter.go
|
UTF-8
| 453 | 3.125 | 3 |
[
"CC-BY-3.0"
] |
permissive
|
[
"CC-BY-3.0"
] |
permissive
|
// Package svg provides an API for generating Scalable Vector Graphics (SVG)
package svg
import (
"io"
"net/http"
)
// HttpAdapter wraps an f(io.Writer) function to become an http.HandlerFunc
// function, and also sets the correct HTTP header SVG mime type for the browser
func HttpAdapter(f func(w io.Writer)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/svg+xml")
f(w)
}
}
| true |
5b367f90704d65c32c41889d3a5458be08efe63d
|
Go
|
baixingdong/ikgo
|
/IKSegmenter.go
|
UTF-8
| 2,313 | 3.125 | 3 |
[] |
no_license
|
[] |
no_license
|
package ikgo
import (
"bufio"
"strings"
)
// 重写ik分词
type IKSegmenter struct {
reader *bufio.Reader
context *AnalyzeContext
segmenters []ISegmenter
arbitrator IKArbitrator
useSmart bool
}
func init() {
initCNQS()
initLS()
}
func NewIKSegmenter(input string, useSmart bool) *IKSegmenter {
ret := &IKSegmenter{
reader: bufio.NewReader(strings.NewReader(input)),
context: NewAnalyzeContext(useSmart),
arbitrator: IKArbitrator{},
useSmart: useSmart,
}
ret.loadSegmenters()
return ret
}
/**
* 初始化词典,加载子分词器实现
* @return List<ISegmenter>
*/
func (s *IKSegmenter) loadSegmenters() {
s.segmenters = []ISegmenter{
NewLetterSegmenter(),
NewCN_QuantifierSegmenter(),
NewCJKSegmenter(),
}
}
/**
* 分词,获取下一个词元
* @return Lexeme 词元对象
* @throws java.io.IOException
*/
func (s *IKSegmenter) Next() *Lexeme {
var l *Lexeme = s.context.getNextLexeme()
for l == nil {
/*
* 从reader中读取数据,填充buffer
* 如果reader是分次读入buffer的,那么buffer要 进行移位处理
* 移位处理上次读入的但未处理的数据
*/
available := s.context.fillBuffer(s.reader)
if available <= 0 {
//reader已经读完
s.context.reset()
return nil
}
//初始化指针
s.context.initCursor()
for {
//遍历子分词器
for _, segmenter := range s.segmenters {
segmenter.analyze(s.context)
}
//字符缓冲区接近读完,需要读入新的字符
if s.context.needRefillBuffer() {
break
}
//向前移动指针
if !s.context.moveCursor() {
break
}
}
//重置子分词器,为下轮循环进行初始化
for _, segmenter := range s.segmenters {
segmenter.reset()
}
//对分词进行歧义处理
s.arbitrator.process(s.context, s.useSmart)
//将分词结果输出到结果集,并处理未切分的单个CJK字符
s.context.outputToResult()
//记录本次分词的缓冲区位移
s.context.markBufferOffset()
l = s.context.getNextLexeme()
}
return l
}
/**
* 重置分词器到初始状态
* @param input
*/
func (s *IKSegmenter) Reset(input string) {
s.context.reset()
for _, segmenter := range s.segmenters {
segmenter.reset()
}
s.reader = bufio.NewReader(strings.NewReader(input))
}
| true |
5b4b04eafa1c0804c8435a30f03f379d6acc1da7
|
Go
|
shawntoffel/faasgo
|
/rest.go
|
UTF-8
| 1,673 | 2.921875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package faasgo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
func (g Gateway) request(method string, endpoint string, data interface{}, output interface{}) error {
body, err := json.Marshal(data)
if err != nil {
return err
}
req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(body))
if err != nil {
return err
}
if g.user != "" || g.pass != "" {
req.SetBasicAuth(g.user, g.pass)
}
req.Header.Add("Content-Type", "application/json")
return g.doRequest(req, output)
}
func (g Gateway) doRequest(req *http.Request, output interface{}) error {
resp, err := g.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
err = checkErrors(resp)
if err != nil {
return err
}
return decodeJson(resp.Body, output)
}
func (g Gateway) simpleRequest(method string, endpoint string, body []byte) ([]byte, error) {
req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
resp, err := g.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = checkErrors(resp)
if err != nil {
return nil, err
}
return ioutil.ReadAll(resp.Body)
}
func checkErrors(response *http.Response) error {
if response.StatusCode >= 200 && response.StatusCode <= 299 {
return nil
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return fmt.Errorf("%d: %s", response.StatusCode, string(body))
}
func decodeJson(body io.Reader, into interface{}) error {
b, err := ioutil.ReadAll(body)
if err != nil {
return err
}
if b == nil || len(b) < 1 {
return nil
}
return json.Unmarshal(b, &into)
}
| true |
c92c44892c7aa5442cffdb36195112d7171d8805
|
Go
|
Addono/Advent-of-Code-2018
|
/day9/main.go
|
UTF-8
| 1,207 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"./ring"
"fmt"
"gopkg.in/cheggaaa/pb.v1"
"math"
)
func max(data map[int]int) int {
max := math.MinInt8
for _, v := range data {
if v > max {
max = v
}
}
return max
}
func printRing(r *ring.Ring) {
r.Do(func(i interface{}) {fmt.Print(i, " ")})
fmt.Println()
}
func main() {
fmt.Println("Part 1 example:", playGame(9, 25), "(", 32, ")")
fmt.Println("Part 1 demo 1:", playGame(10, 1618), "(", 8317, ")")
fmt.Println("Part 1 demo 5:", playGame(30, 5807), "(", 37305, ")")
fmt.Println("Part 1:", playGame(459, 71790))
fmt.Println("Part 2:", playGame(459, 71790 * 100))
}
func playGame(playerCount int, lastMarbleValue int) int {
score := map[int]int{}
game := ring.New(1)
game.Value = 0
bar := pb.StartNew(lastMarbleValue)
bar.SetWidth(80)
for i := 1; i <= lastMarbleValue; i++ {
bar.Increment()
if i % 23 == 0 {
game = game.Move(-8)
score[i % playerCount] += i + game.Value.(int) // Update the score for the current player
game = game.Pop().Move(1) // Remove the previous marble and continue with the next one.
} else {
marble := ring.New(1)
marble.Value = i
game = game.Link(marble)
}
}
bar.Finish()
return max(score)
}
| true |
54b6d33615d5d22b9282422e2e144b208216030f
|
Go
|
Modelhelper/cli
|
/src/scratchpad/tree/node_test.go
|
UTF-8
| 2,049 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package tree_test
import (
"io/ioutil"
"modelhelper/cli/scratchpad/tree"
"os"
"testing"
)
func TestMaxLen(t *testing.T) {
root := getTree()
actual := tree.MaxLen(root)
expected := 40
if expected != actual {
t.Errorf("MaxLen: expected: %d, got %d", expected, actual)
}
}
func TestPrintTreeWithoutDesc(t *testing.T) {
// setup test
root := getTree()
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
tree.PrintTree(root, "", false)
w.Close()
out, _ := ioutil.ReadAll(r)
os.Stdout = rescueStdout
actual := string(out)
expected := `Root Node
Child 1
Child 1 of Child 1
Child 2 of Child 1
Child 3 of Child 1 - with longest length
`
if actual != expected {
t.Errorf("\nExpected \n%s\n\ngot \n%s", expected, out)
}
}
func TestPrintTreeWithDesc(t *testing.T) {
// setup test
root := getTreeDesc()
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
tree.PrintTree(root, "", true)
w.Close()
out, _ := ioutil.ReadAll(r)
os.Stdout = rescueStdout
actual := string(out)
expected := `Root This is the root node
C1 This is a child description
C1.1 This is a child description
C1.2 This is a child description
C1.3 This is a child description
`
if actual != expected {
t.Errorf("\nExpected \n%s\n\ngot \n%s", expected, out)
}
}
func getTree() tree.Node {
root := tree.Node{Name: "Root Node"}
c1 := tree.Node{Name: "Child 1"}
c1.Add(tree.Node{Name: "Child 1 of Child 1"})
c1.Add(tree.Node{Name: "Child 2 of Child 1"})
c1.Add(tree.Node{Name: "Child 3 of Child 1 - with longest length"})
root.Add(c1)
return root
}
func getTreeDesc() tree.Node {
root := tree.Node{Name: "Root", Description: "This is the root node"}
c1 := tree.Node{Name: "C1", Description: "This is a child description"}
c1.Add(tree.Node{Name: "C1.1", Description: "This is a child description"})
c1.Add(tree.Node{Name: "C1.2", Description: "This is a child description"})
c1.Add(tree.Node{Name: "C1.3", Description: "This is a child description"})
root.Add(c1)
return root
}
| true |
ffab0d69d550261e8596c35c1f4ab38bf6063e92
|
Go
|
nikitakuznetsoff/ozon-links-app
|
/internal/repository/postgres.go
|
UTF-8
| 993 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package repository
import (
"context"
"github.com/jackc/pgx/v4"
"github.com/nikitakuznetsoff/ozon-links-app/internal/models"
)
type PostgreDB struct {
conn *pgx.Conn
}
func CreateRepo(db *pgx.Conn) *PostgreDB {
return &PostgreDB{conn: db}
}
func (db *PostgreDB) GetByLink(url string) (*models.Link, error) {
link := &models.Link{}
err := db.conn.
QueryRow(context.Background(), "select id, url from links where url = $1", url).
Scan(&link.ID, &link.Address)
if err != nil {
return nil, err
}
return link, err
}
func (db *PostgreDB) GetByID(id int) (*models.Link, error) {
link := &models.Link{}
err := db.conn.
QueryRow(context.Background(), "select id, url from links where id = $1", id).
Scan(&link.ID, &link.Address)
if err != nil {
return nil, err
}
return link, err
}
func (db *PostgreDB) Set(link string) error {
_, err := db.conn.
Exec(context.Background(), "insert into links (url) values ($1)", link)
if err != nil {
return err
}
return nil
}
| true |
bdd88214f1b2ab4b4b6f64713a2d94c324f88548
|
Go
|
hzylyq/Book
|
/DataInGo/ch03/answer/doublelinklist/doublelinklist.go
|
UTF-8
| 1,103 | 3.640625 | 4 |
[] |
no_license
|
[] |
no_license
|
package doublelinklist
import "book/DataInGo/ch03/answer/linklist"
type element struct {
Val int
Next *element
Prev *element
}
type DoubleList = *element
func New() DoubleList {
var l DoubleList
l = new(element)
return l
}
// return true if l is empty
func IsEmpty(l linklist.List) bool {
return l.Next == nil
}
// return true if P is the last position in list L
func IsLast(p *linklist.Node) bool {
return p.Next == nil
}
// return the position of X in L
func Find(x int, l linklist.List) *linklist.Node {
p := l.Next
for p != nil && p.Val != x {
p = p.Next
}
return p
}
func FindPrevious(x int, l linklist.List) *linklist.Node {
if l == nil {
return nil
}
p := new(linklist.Node)
p.Val = l.Val
p.Next = l.Next
for p.Next != nil && p.Next.Val != x {
p = p.Next
}
return p
}
// delete first occurrence of x from a list
func Delete(x int, l linklist.List) {
p := FindPrevious(x, l)
if p.Next != nil {
temp := p.Next
p.Next = temp.Next
}
}
func insert(x int, l linklist.List) {
temp := new(linklist.Node)
temp.Val = x
temp.Next = l.Next
l.Next = temp
}
| true |
770d68a8a83131cf3f90d00e2d470a0ef0172c44
|
Go
|
MihaiBlebea/go-event-bus
|
/project/create_handler.go
|
UTF-8
| 1,396 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
package project
import (
"encoding/json"
"errors"
"net/http"
)
type CreateRequest struct {
Name string `json:"name"`
}
type CreateResponse struct {
Token string `json:"token,omitempty"`
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
func CreateHandler(s Service) http.Handler {
validate := func(r *http.Request) (*CreateRequest, error) {
request := CreateRequest{}
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
return &request, err
}
if request.Name == "" {
return &request, errors.New("invalid request param name")
}
return &request, nil
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response := CreateResponse{}
request, err := validate(r)
if err != nil {
response.Message = err.Error()
sendResponse(w, response, http.StatusBadRequest)
return
}
token, err := s.Create(request.Name)
if err != nil {
response.Message = err.Error()
sendResponse(w, response, http.StatusBadRequest)
return
}
response.Success = true
response.Token = token
sendResponse(w, response, http.StatusOK)
})
}
func sendResponse(w http.ResponseWriter, resp interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
b, _ := json.Marshal(resp)
w.Write(b)
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.