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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cd2b4d2de0b09e7e55dc347bfe007f2e7246075
|
Go
|
bbhunter/rescope
|
/internal/burp/burp.go
|
UTF-8
| 5,579 | 2.84375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// Author: Daniel Antonsen (@root4loot)
// Distributed Under MIT License
//
// Package burp involves parsing list of scope targets to Burp
// compatible JSON (Regex)
package burp
import (
"bufio"
"encoding/json"
"fmt"
"regexp"
"strings"
File "github.com/root4loot/rescope/pkg/file"
)
// Scope is the JSON structure that burp wants
type Scope struct {
Target struct {
Scope struct {
AdvancedMode bool `json:"advanced_mode"`
Exclude []Exclude `json:"exclude"`
Include []Include `json:"include"`
} `json:"scope"`
} `json:"target"`
}
// Include host details
type Include struct {
Enabled bool `json:"enabled"`
File string `json:"file"`
Host string `json:"host"`
Port string `json:"port"`
Protocol string `json:"protocol"`
}
// Exclude host details
type Exclude struct {
Enabled bool `json:"enabled"`
File string `json:"file"`
Host string `json:"host"`
Port string `json:"port"`
Protocol string `json:"protocol"`
}
// IncludeSlice contains Include structs
type IncludeSlice struct {
Include []Include
}
// ExcludeSlice contains Enclude structs
type ExcludeSlice struct {
Exclude []Exclude
}
// var containing IncludeSlice
var incslice IncludeSlice
// var containing ExcludeSlice
var exslice ExcludeSlice
// Parse takes slices containing regex matches and turns them into Burp
// compatible JSON. Regex matches are split into groups. See internal scope package.
// Returns JSON data as byte
func Parse(Includes, Excludes [][]string) []byte {
var host, scheme, port, path string
var cludes [][][]string
cludes = append(cludes, Includes)
cludes = append(cludes, Excludes)
// file containing servicenames and ports
fr := File.ReadFromRoot("configs/known-ports.txt", "pkg")
for i, clude := range cludes {
for _, item := range clude {
ip := regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)
if ip.MatchString(item[0]) {
for _, ip := range item {
host := parseHost(ip)
scheme = "Any"
if i == 0 {
add(scheme, host, "^(80|443)$", path, false)
} else {
add(scheme, host, "^(80|443)$", path, true)
}
}
} else {
scheme = strings.TrimRight(item[1], "://")
host = item[2] + item[3] + item[4]
port = strings.TrimLeft(item[6], ":")
path = item[7]
//fmt.Println("S:" + scheme + "H:" + host + "PO:" + port + "PA:" + path)
scheme, port = parseSchemeAndPort(fr, scheme, port)
host = parseHost(host)
path = parseFile(path)
if i == 0 {
add(scheme, host, port, path, false)
} else {
add(scheme, host, port, path, true)
}
}
}
}
// scope object
scope := Scope{}
scope.Target.Scope.AdvancedMode = true
// add include/exclude slices
scope.Target.Scope.Include = incslice.Include
scope.Target.Scope.Exclude = exslice.Exclude
// parse pretty json
json, err := json.MarshalIndent(scope, "", " ")
if err != nil {
fmt.Println("json err:", err)
}
return json
}
// // add match to appropriate list
func add(scheme, host, port, path string, exclude bool) {
if !exclude {
incslice.Include = append(incslice.Include, Include{Enabled: true, File: path, Host: host, Port: port, Protocol: scheme})
} else {
exslice.Exclude = append(exslice.Exclude, Exclude{Enabled: true, File: path, Host: host, Port: port, Protocol: scheme})
}
}
// parseSchemeAndPort sets scheme and ports accordingly
// parseHost parse/set scheme & ports accordingly
// returns scheme, port (string) expressions
func parseSchemeAndPort(services []byte, scheme, port string) (string, string) {
re := regexp.MustCompile(`([a-zA-Z0-9-]+)\s+(\d+)`) // for configs/services
// re groups: 0. full match - [ftp 21]
// 1. service - [ftp] 21
// 2. port - ftp [21]
if isVar(scheme) && !isVar(port) {
// set corresponding port from configs/services
scanner := bufio.NewScanner(strings.NewReader(string(services[:])))
for scanner.Scan() {
match := re.FindStringSubmatch(scanner.Text())
if scheme == match[1] {
port = "^" + match[2] + "$"
}
}
} else if !isVar(scheme) && !isVar(port) {
// set port to 80, 443
port = "^(80|443)$"
} else if isVar(scheme) && isVar(port) {
// set whatever port + service port
if scheme == "http" {
port = "^(80|" + port + ")$"
} else if scheme == "https" {
port = "^(443|" + port + ")$"
} else {
port = "^" + port + "$"
}
} else if isVar(port) {
port = "^" + port + "$"
}
// set "Any" when not http(s)
if scheme != "http" && scheme != "https" {
scheme = "Any"
}
return scheme, port
}
// parseHost parse host portion
// returns host (string) expression
func parseHost(host string) string {
if isVar(host) {
if strings.Contains(host, "*") {
host = strings.Replace(host, "*", `[\S]*`, -1)
}
host = strings.Replace(host, ".", `\.`, -1)
host = "^" + host + "$"
}
return host
}
// parseFile parse path portion
// returns path (string) expression
func parseFile(path string) string {
if isVar(path) {
// replace wildcard
path = strings.Replace(path, "*", `[\S]*`, -1)
// escape '.'
path = strings.Replace(path, ".", `\.`, -1)
// escape '/'
path = strings.Replace(path, "/", `\/`, -1)
// add wildcard after dir suffix
// note: this is not really needed as
// burp will treat blank files as wildcards
if strings.HasSuffix(path, "/") {
path = path + `[\S]*`
}
path = "^" + path + "$"
} else {
path = `^[\S]*$`
}
return path
}
// isVar returns bool depening on len of var
func isVar(s string) bool {
if len(s) > 0 {
return true
}
return false
}
| true |
61c724c0b66d45fbd9c43eb35b880a638a197819
|
Go
|
yoshipaulbrophy/gapid
|
/framework/binary/object.go
|
UTF-8
| 4,621 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to 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 binary
import "fmt"
// Object is the interface to any class that wants to be encoded/decoded.
type Object interface {
// Class returns the serialize information and functionality for this type.
// The method should be valid on a nil pointer.
Class() Class
}
// ObjectCast is automatically called by the generated decoders.
func ObjectCast(obj Object) Object {
return obj
}
// UpgradeDecoder provides a decoder interface which maybe used to
// decode a stream from an old version into a newer version.
type UpgradeDecoder interface {
// New constructs a new Object that this decoder handles.
// For a frozen decoder, this would be the new version, not the frozen one, and as such the type returned may not
// match the schema this decoder was registered against.
New() Object
// DecodeTo reads into the supplied object from the supplied Decoder.
// The object must be the same concrete type that New would create, the
// implementation is allowed to panic if it is not.
DecodeTo(Decoder, Object)
}
// Class represents a struct type in the binary registry.
type Class interface {
// Encode writes the supplied object to the supplied Encoder.
// The object must be a type the Class understands, the implementation is
// allowed to panic if it is not.
Encode(Encoder, Object)
// DecodeTo reads into the supplied object from the supplied Decoder.
// The object must be a type the Class understands, the implementation is
// allowed to panic if it is not.
DecodeTo(Decoder, Object)
// Returns the type descriptor for the class.
Schema() *Entity
}
type FrozenClassBase struct{}
// FrozenClassBase provides Encode() so that they satisfy the above Class
// interface, but they should never be called.
func (c *FrozenClassBase) Encode(e Encoder, o Object) {
e.SetError(fmt.Errorf(
"Attempt to encode a frozen object of type %T id %v", o, o.Class().Schema()))
}
// Generate is used to tag structures that need an auto generated Class.
// The codergen function searches packages for structs that have this type as an
// anonymous field, and then automatically generates the encoding and decoding
// functionality for those structures. For example, the following struct would
// create the Class with methods needed to encode and decode the Name and Value
// fields, and register that class.
// The embedding will also fully implement the binary.Object interface, but with
// methods that panic. This will get overridden with the generated Methods.
// This is important because it means the package is resolvable without the
// generated code, which means the types can be correctly evaluated during the
// generation process.
//
// type MyNamedValue struct {
// binary.Generate
// Name string
// Value []byte
// }
//
// Code generation can be customized with tags:
// type MySomethingThatWontHaveAJavaEquivalent struct {
// binary.Generate `java:"disable"`
// }
//
// We currently use the following tags:
// cpp
// java
// disable
// display
// globals
// id
// identity
// implements
// javaDefineEmptyArrays:"true"
// If applied to a struct, any slice fields being read from the wire that
// have a length of zero will be set to the same instance of an empty array
// to avoid unnecessary allocations. e.g. ...service.atom.Observations.
// version
//
type Generate struct{}
func (Generate) Class() Class { panic("Class() not implemented") }
var _ Object = Generate{} // Verify that Generate implements Object.
// Frozen is used to tag structures that represent past versions of types
// which may appear in old capture files. Frozen must be include a "name" tag
// which identifies the name of the struct now in use. Manual upgrading is
// provided with a function of the form:
//
// func (before *FrozenStruct) upgrade(after *GenerateStruct)
//
// See binary/test/frozen.go for examples
type Frozen struct{}
func (Frozen) Class() Class { panic("Class() not implemented") }
var _ Object = Frozen{} // Verify that Frozen implements Object.
| true |
4efa85a3dc0c597a770c011329324de4759b0b51
|
Go
|
Ysunil016/GoLang
|
/CodingChallenge/June/WeekOne/DeleteNodeInLinkedLIst/Start.go
|
UTF-8
| 356 | 3.53125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
// ListNode ...
type ListNode struct {
Val int
Next *ListNode
}
func main() {
list := &ListNode{10, &ListNode{20, &ListNode{30, &ListNode{}}}}
deleteNode(list)
}
func deleteNode(node *ListNode) {
PrevNode := &ListNode{}
for node.Next != nil {
node.Val = node.Next.Val
PrevNode = node
node = node.Next
}
PrevNode.Next = nil
}
| true |
3083b5a32db1eba8f2f065a3d7ceb2c88ba37a6a
|
Go
|
sergripenko/taxi_service
|
/applications/delivery/http/handler.go
|
UTF-8
| 806 | 2.640625 | 3 |
[] |
no_license
|
[] |
no_license
|
package http
import (
"net/http"
"taxi_service/applications"
"taxi_service/models"
"github.com/gin-gonic/gin"
)
type Handler struct {
useCase applications.UseCase
}
func NewHandler(useCase applications.UseCase) *Handler {
return &Handler{
useCase: useCase,
}
}
type getApplication struct {
Application string `json:"application"`
}
func (h *Handler) GetApplication(c *gin.Context) {
appKey := h.useCase.GetApplication(c.Request.Context())
c.JSON(http.StatusOK, &getApplication{
Application: appKey,
})
}
type getAllApplications struct {
Applications []*models.Application `json:"applications"`
}
func (h *Handler) GetAllApplications(c *gin.Context) {
apps := h.useCase.GetAllApplications(c.Request.Context())
c.JSON(http.StatusOK, &getAllApplications{
Applications: apps,
})
}
| true |
8cc94ee84535dea0b9a388609b3f091d96242fa1
|
Go
|
anindyaSeng/microservices
|
/mvc-grpc/app/app.go
|
UTF-8
| 1,738 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package app
import (
"context"
"fmt"
"log"
"net"
"github.com/anindyaSeng/microservices/mvc-grpc/api"
"github.com/anindyaSeng/microservices/mvc-grpc/controllers"
"github.com/anindyaSeng/microservices/mvc-grpc/services"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
port = ":50051"
)
type server struct {
api.UnimplementedUserServiceServer
}
// GetUser implements api.GetUser
func (s *server) GetUser(ctx context.Context, in *api.UserIDRequest) (*api.UserDataReply, error) {
log.Printf("Received User data request for User Id: %v", in.GetId())
user, err := services.GetUser(in.GetId())
if err != nil {
return &api.UserDataReply{IsFound: false, UserData: nil}, fmt.Errorf("User for user id %v not found", in.GetId())
}
return &api.UserDataReply{IsFound: true, UserData: user}, nil
/*if id := in.GetId(); id != 123 {
return &api.UserDataReply{IsFound: false, UserData: nil}, fmt.Errorf("User for user id %v not found", id)
}
return &api.UserDataReply{IsFound: true,
UserData: &api.UserData{
Id: 123,
FirstName: "ab",
LastName: "cd",
Email: "[email protected]",
},
}, nil*/
}
// StartApp -- initialize the app and listen for grpc calls
func StartApp() {
// Start the controller
controllers.InitUserController()
// Now listen to gRPC calls
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("Failed to listen : %v", err)
}
s := grpc.NewServer()
api.RegisterUserServiceServer(s, &server{})
reflection.Register(s) // Needed for reflection API, only then grpCui finds it
//https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to serve : %v", err)
}
}
| true |
d29112a863b158d757e35cff2ca23975b35421d6
|
Go
|
chadrbean/golang
|
/learning/buble_sorting/main.go
|
UTF-8
| 523 | 3.15625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
func main(){
sortArray := [...]int{5,10,6,3,7,8, 10, 24, 44, 54, 2, 4, 56}
findLen := len(sortArray)
preSort := [2]int{} //create array size 2 for sorting each pair
for ii:=0; ii <= 6; ii++ {
fmt.Print(ii)
for i := 0; i <= findLen; i++ {
if i == findLen -1 {
break
}
if sortArray[i] > sortArray[i+1] {
preSort[0] = sortArray[i+1]
preSort[1] = sortArray[i]
sortArray[i] = preSort[0]
sortArray[i+1] = preSort[1]
}
}
fmt.Print(sortArray, "\n")
}
}
| true |
815c5072334786813e208c626fdab35e41d625dd
|
Go
|
gyb333/StudyGolang
|
/src/basic/study_reflect.go
|
UTF-8
| 1,700 | 3.28125 | 3 |
[] |
no_license
|
[] |
no_license
|
package basic
import (
"fmt"
"reflect"
"strings"
. "unsafe"
)
func ReflectMain() {
ret := CallMethod(func(arg interface{}) (string, bool) {
fmt.Println(arg)
return "test", true
}, []interface{}{"gyb", 33})
for i, v := range ret {
fmt.Printf("%T,%v", v, v)
fmt.Println(i, v,v.Interface(),v.Type())
switch v.Interface().(type) {
case string:
fmt.Println(v.String(),reflect.TypeOf(""))
case bool:
fmt.Println(v.Bool(),reflect.TypeOf(false))
}
}
}
func ReflectData() {
x := 1
fmt.Printf("%T,%#v,%#x,%v\n", x, &x, Pointer(&x), x)
d := reflect.ValueOf(&x).Elem() // d refers to the variable x
fmt.Printf("%T,%#v,%#x,%v\n", d, &d, Pointer(&d), d)
d.Set(reflect.ValueOf(2))
fmt.Println(&x, x, d.Addr(), d)
px := d.Addr().Interface().(*int) // px := &x
*px = 3 // x = 3
fmt.Println(px, x, d) // "3"
}
func Equal() {
got := strings.Split("a:b:c", ":")
want := []string{"a", "b", "c"}
fmt.Println(reflect.DeepEqual(got, want))
var a, b []string = nil, []string{}
fmt.Println(reflect.DeepEqual(a, b)) // "false"
var c, d map[string]int = nil, make(map[string]int)
fmt.Println(reflect.DeepEqual(c, d)) // "false"
fmt.Println(reflect.DeepEqual([]int{1, 2, 3}, []int{1, 2, 3})) // "true"
fmt.Println(reflect.DeepEqual([]string{"foo"}, []string{"bar"})) // "false"
fmt.Println(reflect.DeepEqual([]string(nil), []string{})) // "false"
fmt.Println(reflect.DeepEqual(map[string]int(nil), map[string]int{})) // "false"
}
func CallMethod(method interface{}, params interface{}) []reflect.Value {
fv := reflect.ValueOf(method)
args := []reflect.Value{reflect.ValueOf(params)}
return fv.Call(args)
}
| true |
7dd69ea4a6a9b03a904f0a2df337b40b4ac68726
|
Go
|
kevin0814/go
|
/指针.go
|
UTF-8
| 1,485 | 4.6875 | 5 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
/*
指针:pointer
存储了另一个变量的内存地址的变量。
*/
//1.定义一个int类型的变量
//Go 语言的取地址符是 &
//声明指针,*T是指针变量的类型,它指向T类型的值。 var var_name *var-type
//var-type 为指针类型,var_name 为指针变量名,* 号用于指定变量是作为一个指针。
a := 10
fmt.Println("a的数值是:",a) //10
fmt.Printf("%T\n",a) //int
fmt.Printf("a的地址是:%p\n",&a) //0xc00008a008
//2.创建一个指针变量,用于存储变量a的地址
var p1 *int
fmt.Println(p1) //<nil>,空指针
p1 = &a //p1指向了a的内存地址
fmt.Println("p1的数值:",p1) //p1中存储的是a的地址
fmt.Printf("p1自己的地址:%p\n",&p1)
fmt.Println("p1的数值,是a的地址,该地址存储的数据:",*p1)//获取指针指向的变量的数值
//3.操作变量,更改数值 ,并不会改变地址
a = 100
fmt.Println(a)
fmt.Printf("%p\n",&a)
//4.通过指针,改变变量的数值
*p1 = 200
fmt.Println(a)
//5.指针的指针
var p2 **int
fmt.Println(p2)
p2 = &p1
fmt.Printf("%T,%T,%T\n",a,p1,p2) //int, *int, **int
fmt.Println("p2的数值:",p2) //p1的地址
fmt.Printf("p2自己的地址:%p\n",&p2)
fmt.Println("p2中存储的地址,对应的数值,就是p1的地址,对应的数据:",*p2)
fmt.Println("p2中存储的地址,对应的数值,再获取对应的数值:",**p2)
}
| true |
b35c8d8cba54a92e12ae234419b390cbb167d275
|
Go
|
guoruibiao/mailer
|
/mailer.go
|
UTF-8
| 5,147 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package mailer
import (
"strconv"
"net"
"github.com/pkg/errors"
"net/smtp"
"encoding/base64"
"bytes"
"fmt"
"strings"
"io/ioutil"
)
// reference from http://www.361way.com/golang-email-attachment/5856.html
// ServerConfig: config your smtp mail server
type ServerConfig struct {
host string
port int
}
// Mailer play as the master of email dispatcher
type Mailer struct{
serverConfig ServerConfig
auth smtp.Auth
}
// NewMailer return the instance by configing your SMTP server
func NewMailer(host string, port int) *Mailer {
return &Mailer{
ServerConfig{
host:host,
port:port,
},
nil,
}
}
// Auth just only send the credentials if the connection is using TLS
// or is connected to localhost. Otherwise authentication will fail with an
// error, without sending the credentials.
// for more details which defined in RFC 4616.
func (mailer *Mailer)Auth(username, authencode string) error {
address := mailer.serverConfig.host + ":" + strconv.Itoa(mailer.serverConfig.port)
host, port, err := net.SplitHostPort(address)
if err != nil {
return err
}
if _, err = strconv.Atoi(port); err != nil {
return errors.New("mial server port is not a valid number, error:" + err.Error())
}
auth := smtp.PlainAuth("", username, authencode, host)
mailer.auth = auth
return nil
}
// Send send your plain text email or simple attachment contains plain text
// todo handle the attachment whose's size > 50KB, which will cause `421 Read data from client error`
func (mailer *Mailer)Send(from string, to, cc []string, title, subject, body string) (bool, error) {
// 设置邮件header啥的
message := NewMailMessage("MY_BOUNDARY_DELIMITER")
message.addHeader(from, to, cc, title, subject)
// 添加邮件正文
message.addContent(body)
//message.addAttach("/Users/biao/go/src/github.com/guoruibiao/commands/commands.go", "text/plain")
//message.addAttach("/Users/biao/Desktop/d6154ea0a1cfdb98e9bafc03bd31ffcb.png", "image/png")
//message.addAttach("/Users/biao/Desktop/example.tar.gz.png", "application/octet-stream")
serverName := mailer.serverConfig.host + ":" + strconv.Itoa(mailer.serverConfig.port)
err := smtp.SendMail(serverName, mailer.auth, from, to, message.outlet())
if err != nil {
fmt.Println(err)
}
return true, nil
}
// MIMEMessage MIME,Multipurpose Internet Mail Extensions
// which extends the standard internet protocol, so we can free to send multi data
type MIMEMessage struct {
boundary string
container *bytes.Buffer
}
func NewMailMessage(boundary string) *MIMEMessage{
return &MIMEMessage{
boundary:boundary,
container: bytes.NewBuffer(nil),
}
}
func (mime *MIMEMessage)addHeader(from string, to []string, cc []string, title, subject string) {
tolist := strings.Join(to, ",")
cclist := strings.Join(cc, ",")
header := fmt.Sprintf("From: %s<%s>\r\nTo: %s\r\nCC: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\n", from, from, tolist, cclist, subject)
mime.container.WriteString(header)
mime.container.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\r\n", mime.boundary))
mime.container.WriteString(fmt.Sprintf("Content-Description: %s\r\n", title))
}
// addContent append the content to your email
func (mime *MIMEMessage)addContent(content string) {
mime.container.WriteString(fmt.Sprintf("--%s\r\n", mime.boundary))
mime.container.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
mime.container.WriteString(content)
}
// addAttach TODO: fix `421 Read data from client error` which caused by whose size > 50KB
func (mime *MIMEMessage)addAttach(filepath string, mimetype string) error{
pathParams := strings.Split(filepath, "/")
if len(pathParams) <= 0 {
return errors.New("No such an attach file in path: " + filepath)
}
filename := pathParams[len(pathParams)-1]
// 添加 附件栏内容相关元数据
mime.container.WriteString(fmt.Sprintf("\r\n--%s\r\n", mime.boundary))
//mime.container.WriteString(fmt.Sprintf("Content-Type: %s\r\n", mimetype))
mime.container.WriteString("image/png\r\n")
mime.container.WriteString(fmt.Sprintf("Content-Description: %s\r\n", filename))
mime.container.WriteString(fmt.Sprintf("Content-Disposition: attachment; filename=\"%s\"\r\n\r\n", filename))
// 读取文件并进行编码处理
data, err := ioutil.ReadFile(filepath)
if err != nil {
return err
}
if mimetype != "text/plain" {
mime.container.WriteString(fmt.Sprintf("Content-Transfer-Encoding: base64\r\n"))
edata := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
base64.StdEncoding.Encode(edata, data)
// 切一下,复用下变量
data = edata
}
mime.container.Write(data)
fmt.Println(string(data))
// 防止添加多个附件时缺少额外的分隔
mime.container.WriteString("\r\n")
return nil
}
// outlet take all sections of this mail into bytes for sending.
func (mime *MIMEMessage) outlet() []byte {
if mime.container != nil && mime.container.Len()>0 {
// 邮件正式结束
mime.container.WriteString(fmt.Sprintf("\r\n--%s--\r\n\r\n", mime.boundary))
}else {
mime.container.WriteString(fmt.Sprintf("\r\n--%s--\r\n\r\n", mime.boundary))
}
return mime.container.Bytes()
}
| true |
d9868fab5be2332cd127f88f07a72acbd7620e6b
|
Go
|
hflemmen/project_v3
|
/orders/elevio/ordStruct/ordStruct.go
|
UTF-8
| 2,306 | 3.171875 | 3 |
[] |
no_license
|
[] |
no_license
|
package ordStruct
import "fmt"
import "time"
const DOOR_OPEN_TIME = 3 * time.Second
const NUMFLOORS = 4
type behaviourType int
const (
E_Moving behaviourType = 2
E_Idle = 1
E_DoorOpen = 0
)
type MotorDirection int
const (
MD_Up MotorDirection = 1
MD_Down = -1
MD_Stop = 0
)
type ButtonType int
const (
BT_HallUp ButtonType = 0
BT_HallDown = 1
BT_Cab = 2
)
type OrderType int
const (
OT_Up OrderType = 1
OT_Down = -1
OT_Cab = 0
)
type ButtonEvent struct {
Floor int
Direction int
Button ButtonType
}
type LightType [2][NUMFLOORS]bool
type Elevator struct {
Floor int
Dir MotorDirection
Order [3][NUMFLOORS]bool
Behaviour behaviourType
LightMatrix LightType
}
func ElevatorInit() (e Elevator) {
e = Elevator{Dir: 0}
return
}
func (e *Elevator) Duplicate() (e2 Elevator) {
e2 = *e
return
}
func (e *Elevator) AddOrder(button int, floor int) {
e.Order[button][floor] = true
}
func (e *Elevator) RemoveOrder(button ButtonType, floor int) {
e.Order[int(button)][floor] = false
}
func (e *Elevator) Differences(e2 Elevator) ([]int, []int) {
buttons := make([]int, 0)
floors := make([]int, 0)
for i := 0; i < 3; i++ {
for j := 0; j < NUMFLOORS; j++ {
if e2.Order[i][j] == true && e.Order[i][j] == false {
buttons = append(buttons, i)
floors = append(floors, j)
}
}
}
return buttons, floors
}
func (e *Elevator) ClearOrders() {
for i := 0; i < 3; i++ {
for j := 0; j < 4; j++ {
e.Order[i][j] = false
}
}
}
func (e *Elevator) PrintOrders() {
fmt.Print("[ ")
for i := 0; i < 3; i++ {
fmt.Println()
for j := 0; j < 4; j++ {
fmt.Print(e.Order[i][j], " ")
}
}
fmt.Print("]\n")
}
func (e *Elevator) PrintLightMatrix() {
fmt.Print("[ ")
for i := 0; i < 2; i++ {
fmt.Println()
for j := 0; j < 4; j++ {
fmt.Print(e.LightMatrix[i][j], " ")
}
}
fmt.Print("]\n")
}
func (e *Elevator) CheckOrderUpdate() ButtonEvent {
for btn := 0; btn < 3; btn++ {
for floor := 0; floor < NUMFLOORS; floor++ {
if e.Order[btn][floor] == false && e.LightMatrix[btn][floor] == true {
return ButtonEvent{Button: ButtonType(btn), Floor: floor}
}
}
}
return ButtonEvent{Floor: -1}
}
| true |
8eca79ec398f856d8b70dfb52e7cb9080395351b
|
Go
|
digideskio/httpexpect
|
/value_test.go
|
UTF-8
| 6,842 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package httpexpect
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestValueFailed(t *testing.T) {
chain := makeChain(newMockReporter(t))
chain.fail("fail")
value := &Value{chain, nil}
value.chain.assertFailed(t)
assert.False(t, value.Object() == nil)
assert.False(t, value.Array() == nil)
assert.False(t, value.String() == nil)
assert.False(t, value.Number() == nil)
assert.False(t, value.Boolean() == nil)
value.Object().chain.assertFailed(t)
value.Array().chain.assertFailed(t)
value.String().chain.assertFailed(t)
value.Number().chain.assertFailed(t)
value.Boolean().chain.assertFailed(t)
value.Null()
value.NotNull()
}
func TestValueCastNull(t *testing.T) {
reporter := newMockReporter(t)
var data interface{}
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertFailed(t)
NewValue(reporter, data).Null().chain.assertOK(t)
}
func TestValueCastIndirectNull(t *testing.T) {
reporter := newMockReporter(t)
var data []interface{}
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertFailed(t)
NewValue(reporter, data).Null().chain.assertOK(t)
}
func TestValueCastBad(t *testing.T) {
reporter := newMockReporter(t)
data := func() {}
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertFailed(t)
NewValue(reporter, data).Null().chain.assertFailed(t)
}
func TestValueCastObject(t *testing.T) {
reporter := newMockReporter(t)
data := map[string]interface{}{}
NewValue(reporter, data).Object().chain.assertOK(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertOK(t)
NewValue(reporter, data).Null().chain.assertFailed(t)
}
func TestValueCastArray(t *testing.T) {
reporter := newMockReporter(t)
data := []interface{}{}
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertOK(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertOK(t)
NewValue(reporter, data).Null().chain.assertFailed(t)
}
func TestValueCastString(t *testing.T) {
reporter := newMockReporter(t)
data := ""
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertOK(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertOK(t)
NewValue(reporter, data).Null().chain.assertFailed(t)
}
func TestValueCastNumber(t *testing.T) {
reporter := newMockReporter(t)
data := 0.0
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertOK(t)
NewValue(reporter, data).Boolean().chain.assertFailed(t)
NewValue(reporter, data).NotNull().chain.assertOK(t)
NewValue(reporter, data).Null().chain.assertFailed(t)
}
func TestValueCastBoolean(t *testing.T) {
reporter := newMockReporter(t)
data := false
NewValue(reporter, data).Object().chain.assertFailed(t)
NewValue(reporter, data).Array().chain.assertFailed(t)
NewValue(reporter, data).String().chain.assertFailed(t)
NewValue(reporter, data).Number().chain.assertFailed(t)
NewValue(reporter, data).Boolean().chain.assertOK(t)
NewValue(reporter, data).NotNull().chain.assertOK(t)
NewValue(reporter, data).Null().chain.assertFailed(t)
}
func TestValueGetObject(t *testing.T) {
type (
myMap map[string]interface{}
)
reporter := newMockReporter(t)
data1 := map[string]interface{}{"foo": 123.0}
value1 := NewValue(reporter, data1)
inner1 := value1.Object()
inner1.chain.assertOK(t)
inner1.chain.reset()
assert.Equal(t, data1, inner1.Raw())
data2 := myMap{"foo": 123.0}
value2 := NewValue(reporter, data2)
inner2 := value2.Object()
inner2.chain.assertOK(t)
inner2.chain.reset()
assert.Equal(t, map[string]interface{}(data2), inner2.Raw())
}
func TestValueGetArray(t *testing.T) {
type (
myArray []interface{}
)
reporter := newMockReporter(t)
data1 := []interface{}{"foo", 123.0}
value1 := NewValue(reporter, data1)
inner1 := value1.Array()
inner1.chain.assertOK(t)
inner1.chain.reset()
assert.Equal(t, data1, inner1.Raw())
data2 := myArray{"foo", 123.0}
value2 := NewValue(reporter, data2)
inner2 := value2.Array()
inner2.chain.assertOK(t)
inner2.chain.reset()
assert.Equal(t, []interface{}(data2), inner2.Raw())
}
func TestValueGetString(t *testing.T) {
reporter := newMockReporter(t)
value := NewValue(reporter, "foo")
inner := value.String()
inner.chain.assertOK(t)
inner.chain.reset()
assert.Equal(t, "foo", inner.Raw())
}
func TestValueGetNumber(t *testing.T) {
type (
myInt int
)
reporter := newMockReporter(t)
data1 := 123.0
value1 := NewValue(reporter, data1)
inner1 := value1.Number()
inner1.chain.assertOK(t)
inner1.chain.reset()
assert.Equal(t, data1, inner1.Raw())
data2 := 123
value2 := NewValue(reporter, data2)
inner2 := value2.Number()
inner2.chain.assertOK(t)
inner2.chain.reset()
assert.Equal(t, float64(data2), inner2.Raw())
data3 := myInt(123)
value3 := NewValue(reporter, data3)
inner3 := value3.Number()
inner3.chain.assertOK(t)
inner3.chain.reset()
assert.Equal(t, float64(data3), inner3.Raw())
}
func TestValueGetBoolean(t *testing.T) {
reporter := newMockReporter(t)
value1 := NewValue(reporter, true)
inner1 := value1.Boolean()
inner1.chain.assertOK(t)
inner1.chain.reset()
assert.Equal(t, true, inner1.Raw())
value2 := NewValue(reporter, false)
inner2 := value2.Boolean()
inner2.chain.assertOK(t)
inner2.chain.reset()
assert.Equal(t, false, inner2.Raw())
}
| true |
cb95a533b4084d25d3b7df3adeaf907294ad82ba
|
Go
|
MTursynbekov/Tour-Of-Go-Solututions
|
/maps.go
|
UTF-8
| 435 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
words := strings.Fields(s)
word_count := make(map[string]int)
for i, word := range words {
cnt := 0
for j := i; j < len(words); j++ {
if word == words[j] {
cnt += 1
}
}
_, is_exists := word_count[word]
if !is_exists {
word_count[word] = cnt
}
}
return word_count
}
func main() {
wc.Test(WordCount)
}
| true |
601455386aecb7262de04ff91031a5dee27f992a
|
Go
|
schmaluk/todoapp
|
/db/insertUpdate.go
|
UTF-8
| 394 | 2.703125 | 3 |
[] |
no_license
|
[] |
no_license
|
package db
import (
"database/sql"
)
func InsertTodoUser(db *sql.DB, user *TodoUser) (int64, error) {
result, err := db.Exec("INSERT INTO TODO_USER (firstName,lastName,email,password) VALUES ($1,$2,$3,$4)", user.FirstName, user.LastName, user.Email, user.Password)
if err != nil {
return 0, err
}
id, err := result.LastInsertId()
if err != nil {
return 0, err
}
return id, nil
}
| true |
c7ed739cf5d77d95f826db2c72be1fc8e2e4aee2
|
Go
|
skynet0590/atomicSwapTool
|
/server/asset/driver.go
|
UTF-8
| 1,750 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// This code is available on the terms of the project LICENSE.md file,
// also available online at https://blueoakcouncil.org/license/1.0.0.
package asset
import (
"fmt"
"sync"
"github.com/skynet0590/atomicSwapTool/dex"
)
var (
driversMtx sync.Mutex
drivers = make(map[string]Driver)
)
// Driver is the interface required of all assets. Setup should create a
// Backend, but not start the backend connection.
type Driver interface {
Setup(configPath string, logger dex.Logger, network dex.Network) (Backend, error)
DecodeCoinID(coinID []byte) (string, error)
}
// DecodeCoinID creates a human-readable representation of a coin ID for a named
// asset with a corresponding driver registered with this package.
func DecodeCoinID(name string, coinID []byte) (string, error) {
driversMtx.Lock()
drv, ok := drivers[name]
driversMtx.Unlock()
if !ok {
return "", fmt.Errorf("db: unknown asset driver %q", name)
}
return drv.DecodeCoinID(coinID)
}
// Register should be called by the init function of an asset's package.
func Register(name string, driver Driver) {
driversMtx.Lock()
defer driversMtx.Unlock()
if driver == nil {
panic("asset: Register driver is nil")
}
if _, dup := drivers[name]; dup {
panic("asset: Register called twice for asset driver " + name)
}
drivers[name] = driver
}
// Setup sets up the named asset. The RPC connection parameters are obtained
// from the asset's configuration file located at configPath.
func Setup(name, configPath string, logger dex.Logger, network dex.Network) (Backend, error) {
driversMtx.Lock()
drv, ok := drivers[name]
driversMtx.Unlock()
if !ok {
return nil, fmt.Errorf("asset: unknown asset driver %q", name)
}
return drv.Setup(configPath, logger, network)
}
| true |
55b5c3401027c0ece519ca9609a6a5b8bdef0e63
|
Go
|
jani-nykanen/blocked
|
/src/util.go
|
UTF-8
| 1,162 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"errors"
"os"
"github.com/jani-nykanen/blocked/src/core"
)
func getDifficultyName(dif int32) string {
difficultyNames := []string{
"Easy", "Medium", "Hard", "Expert"}
return difficultyNames[core.ClampInt32(dif, 0, int32(len(difficultyNames))-1)]
}
func writeSettingsFile(path string, ev *core.Event) error {
data := make([]byte, 3)
// 'cause you can't typecast bool to byte
data[0] = 0
if ev.IsFullscreen() {
data[0] = 1
}
data[1] = byte(ev.Audio.GetSampleVolume())
data[2] = byte(ev.Audio.GetMusicVolume())
file, err := os.Create(path)
if err != nil {
return err
}
// We could check for errors but why bother
file.Write(data)
file.Close()
return nil
}
func readSettingsFile(path string) (bool, int32, int32, error) {
file, err := os.Open(path)
if err != nil {
return false, 0, 0, err
}
bytes := make([]byte, 3)
var n int
n, err = file.Read(bytes)
if err != nil {
return false, 0, 0, err
}
if n != 3 {
return false, 0, 0, errors.New("missing data in the settings file")
}
ret1 := bytes[0] == 1
ret2 := int32(bytes[1])
ret3 := int32(bytes[2])
return ret1, ret2, ret3, nil
}
| true |
68fdb3578b468d24155582d1a09fe5fd03261c87
|
Go
|
yasam0705/go-structs
|
/main.go
|
UTF-8
| 1,024 | 2.78125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
contacts "contact_list/contactList"
tasklist "contact_list/taskList"
)
func main() {
cont := new(contacts.ContactList)
cont.Create(contacts.Contact{
Id: 10,
FirstName: "Sam",
LastName: "Smith",
Phone: "991234567",
Email: "[email protected]",
})
cont.Create(contacts.Contact{
Id: 12,
FirstName: "Eugene",
LastName: "Williamson",
Phone: "(139)-191-0039",
Email: "[email protected]",
})
// fmt.Println(cont.GetAll())
// cont.Delete(12)
// fmt.Println(cont.Get(12))
taskl := new(tasklist.TaskList)
taskl.Create(tasklist.Task{
Id: 15,
Name: "task15",
Status: "asd",
Priority: "medium",
CreatedAt: "03.10.2021",
CreatedBy: "03.10.2021",
DueDate: "05.10.2021",
})
taskl.Create(tasklist.Task{
Id: 20,
Name: "task20",
Status: "qwerty",
Priority: "important",
CreatedAt: "03.10.2021",
CreatedBy: "03.10.2021",
DueDate: "06.10.2021",
})
// taskl.Delete(20)
// fmt.Println(taskl.GetAll())
}
| true |
cb4ce6891c910cb3f8a38ab2bba3f424d0b7450f
|
Go
|
cmertz/repo-sync
|
/source/source_github.go
|
UTF-8
| 1,161 | 2.6875 | 3 |
[] |
no_license
|
[] |
no_license
|
package source
import (
"context"
"fmt"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
)
// Github is a github source for remotes to sync from
type Github struct {
Username string
Token string
}
// List remote repository urls
func (g Github) List(ctx context.Context) ([]string, error) {
client := githubv4.NewClient(
oauth2.NewClient(
ctx,
oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: g.Token,
}),
),
)
// TODO: pagination
var query struct {
Search struct {
RepositoryCount githubv4.Int
PageInfo struct {
EndCursor githubv4.String
StartCursor githubv4.String
}
Edges []struct {
Node struct {
Repository struct {
SSHURL githubv4.String
} `graphql:"... on Repository"`
}
}
} `graphql:"search(query: $query, type: REPOSITORY, first: 100)"`
}
err := client.Query(ctx, &query, map[string]interface{}{"query": githubv4.String("user:" + g.Username)})
if err != nil {
return nil, fmt.Errorf("List: %w", err)
}
var res []string
for _, edge := range query.Search.Edges {
res = append(res, string(edge.Node.Repository.SSHURL))
}
return res, nil
}
| true |
ab1e1de7f10f08a9a49b4358546945ac8f26f09c
|
Go
|
xeenhl/authService
|
/model/auth.go
|
UTF-8
| 989 | 2.65625 | 3 |
[] |
no_license
|
[] |
no_license
|
package model
import (
"encoding/json"
"github.com/rs/xid"
)
type User struct {
Id xid.ID `json:"id,omitempty"`
Credentials *Credentilas `json:"credentials,omitempty"`
Active bool `json:"active"`
Banned bool `json:"banned"`
SSOData
}
func NewUser(c Credentilas) User {
return User{
Id: xid.New(),
Credentials: &c,
Banned: false,
Active: true,
}
}
type Credentilas struct {
Email string `json:"email"`
Password string `json:"password"`
}
type SSOData struct {
Valid *bool `json:"token_valid,omitempty"`
Claims []Claim `json:"claims,omitempty"`
}
type Claim struct {
Key string
Value interface{}
}
type AuthError struct {
ErrorCode string `json:"error"`
Reason string `json:"reason"`
}
func (err AuthError) Error() string {
return string(err.ToBytes())
}
func (err AuthError) ToBytes() []byte {
b, error := json.Marshal(err)
if error != nil {
return []byte("{}")
}
return b
}
| true |
4276c8655aa01e399353aad60173d1d59e33cf4c
|
Go
|
go-air/dupi
|
/doc.go
|
UTF-8
| 1,586 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2021 the Dupi 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 dupi provides a library for exploring duplicate
// data in large sets of documents.
package dupi
import (
"fmt"
"io"
"io/ioutil"
"os"
)
type Doc struct {
Path string
Start uint32
End uint32
Dat []byte `json:"-"`
}
func NewDoc(path, body string) *Doc {
return &Doc{
Path: path,
Dat: []byte(body)}
}
func (doc *Doc) Load() error {
var (
f *os.File
err error
)
f, err = os.Open(doc.Path)
if err != nil {
return err
}
defer f.Close()
if doc.Start == 0 && doc.End == 0 {
doc.Dat, err = ioutil.ReadAll(f)
if err != nil {
return fmt.Errorf("readall: %w", err)
}
doc.End = uint32(len(doc.Dat))
} else {
_, err = f.Seek(int64(doc.Start), io.SeekStart)
if err != nil {
return fmt.Errorf("seek: %w", err)
}
doc.Dat = make([]byte, doc.End-doc.Start)
_, err = f.ReadAt(doc.Dat, int64(doc.Start))
if err != nil {
return fmt.Errorf("readat %s len=%d at=%d: %w\n", doc.Path, len(doc.Dat), doc.Start, err)
}
}
return nil
}
| true |
b5ddbc8c0d4375cbc94008a34ec93705d6e09499
|
Go
|
lqhcpsgbl/oui_mapping
|
/step1/download_oui_file.go
|
UTF-8
| 959 | 3.328125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
// 下载 OUI 文件,并打印结果
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
// 将 step0 代码写成函数
func GetLastModified() string {
url := "http://standards-oui.ieee.org/oui.txt"
resp, err := http.Head(url)
if err != nil {
log.Fatalln(err)
}
last_modified := resp.Header.Get("Last-Modified")
return last_modified
}
func DownloadOUI() string {
url := "http://standards-oui.ieee.org/oui.txt"
resp, err := http.Get(url)
// Fatalln is equivalent to Println() followed by a call to os.Exit(1).
if err != nil {
log.Fatalln(err)
}
// 关于 defer 查看 defer.md 笔记 , defer需要写在 判断错误之后
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
return string(content)
}
func main() {
fmt.Println(GetLastModified())
fmt.Println(DownloadOUI())
}
| true |
1d5c739a04e9082068f9b63e52875986d058fab3
|
Go
|
mixagd/clothes_go
|
/main.go
|
UTF-8
| 5,413 | 3.015625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "clothes"
password = "clothes"
dbname = "clothes"
)
var db *sql.DB
type Cloth struct {
ID string `json:"id"`
Type string `json:"type"`
Colour string `json:"colour"`
Fit string `json:"fit"`
Owner string `json:"owner"`
}
// var data = []Cloth{
// Cloth{ID: "1", Type: "Blouse", Colour: "Blue", Fit: "Tight", Owner: "Michaila"},
// Cloth{ID: "2", Type: "Blouse", Colour: "White", Fit: "Loose", Owner: "Maria"},
// Cloth{ID: "3", Type: "Blouse", Colour: "Black", Fit: "Loose", Owner: "Maria"},
// Cloth{ID: "4", Type: "Jeans", Colour: "Blue", Fit: "Tight", Owner: "Michaila"},
// Cloth{ID: "5", Type: "Trousers", Colour: "Beige", Fit: "Tight", Owner: "Katerina"},
// }
func getAllClothes(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
rows, err := db.Query("SELECT * FROM clothes")
if err != nil {
// handle this error better than this
panic(err)
}
defer rows.Close()
myRetList := make([]Cloth, 0)
for rows.Next() {
var cloth = Cloth{}
err = rows.Scan(&cloth.ID, &cloth.Type, &cloth.Colour, &cloth.Fit, &cloth.Owner)
if err != nil {
// handle this error
panic(err)
}
myRetList = append(myRetList, cloth)
}
bd, _ := json.Marshal(myRetList)
w.Write(bd)
// get any error encountered during iteration
err = rows.Err()
if err != nil {
panic(err)
}
}
func getClothByID(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
cloth, err := findCloth(vars["id"])
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
}
bd, err := json.Marshal(cloth)
w.Write(bd)
}
func findCloth(id string) (Cloth, error) {
sqlStatement := `SELECT * FROM clothes WHERE id=$1;`
var cloth = Cloth{}
row := db.QueryRow(sqlStatement, id)
err := row.Scan(&cloth.ID, &cloth.Type, &cloth.Colour, &cloth.Fit, &cloth.Owner)
switch err {
case sql.ErrNoRows:
fmt.Println("No rows were returned!")
return Cloth{}, err
case nil:
return cloth, nil
default:
return Cloth{}, err
}
}
func deleteCloth(id string) {
sqlStatement := `DELETE FROM clothes WHERE id = $1;`
_, err := db.Exec(sqlStatement, id)
if err != nil {
panic(err)
}
}
func deleteClothByID(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
deleteCloth(vars["id"])
w.WriteHeader(http.StatusNoContent)
}
func updateClothByIDOLD(w http.ResponseWriter, r *http.Request) {
u := make(map[string]interface{})
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(b, &u)
if err != nil {
panic(err)
}
vars := mux.Vars(r)
strTmpl := `UPDATE clothes SET %s WHERE id = $1;`
vals := make([]interface{}, 0)
vals = append(vals, vars["id"])
strstr := ""
strcomma := ""
cntVal := 2
for k, v := range u {
fmt.Printf("%v => %v\n", k, v)
strstr = strstr + strcomma + fmt.Sprintf("%s=$%d", k, cntVal)
//fmt.Sprintf("%s %s %s = $%d", strcomma, strstr, k, cntVal)
cntVal = cntVal + 1
strcomma = ","
vals = append(vals, v)
}
fmt.Println(strstr)
strQuery := fmt.Sprintf(strTmpl, strstr)
fmt.Printf("%s\n%v\n", strQuery, vals)
w.WriteHeader(http.StatusOK)
}
func updateClothByID(w http.ResponseWriter, r *http.Request) {
var myCloth = Cloth{}
vars := mux.Vars(r)
clothID := vars["id"]
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
u := make(map[string]interface{})
err = json.Unmarshal(b, &u)
var requiredFields = []string{"colour", "fit", "type", "owner"}
var missingFields = make([]string, 0)
allFound := true
for _, k := range requiredFields {
if _, ok := u[k]; !ok {
allFound = false
missingFields = append(missingFields, k)
}
}
if !allFound {
w.WriteHeader(http.StatusBadRequest)
bd := fmt.Sprintf("Missing fields: %v", missingFields)
w.Write([]byte(bd))
return
}
err = json.Unmarshal(b, &myCloth)
if err != nil {
panic(err)
}
strSQL := `UPDATE clothes SET type=$1, colour=$2,
fit=$3, owner=$4 WHERE id=$5;
`
_, err = db.Exec(strSQL, myCloth.Type, myCloth.Colour,
myCloth.Fit,
myCloth.Owner, clothID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
cloclo, err := findCloth(clothID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
bdExplain := fmt.Sprintf("Error while retrieving cloth with id %s: %v",
clothID, err.Error())
w.Write([]byte(bdExplain))
return
}
bd, err := json.Marshal(cloclo)
w.WriteHeader(http.StatusOK)
w.Write(bd)
}
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
var err error
db, err = sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
r := mux.NewRouter()
r.HandleFunc("/clothes", getAllClothes).Methods("GET")
r.HandleFunc("/clothes/{id}", getClothByID).Methods("GET")
r.HandleFunc("/clothes/{id}", deleteClothByID).Methods("DELETE")
r.HandleFunc("/clothes/{id}", updateClothByID).Methods("PUT")
http.ListenAndServe("0.0.0.0:8080", r)
}
| true |
d72ded987f3b74a34553b8593f7c5ab3db826aeb
|
Go
|
kashitaka/programing-langage-go-syakyo
|
/chap7/exercise7.10/palindrome.go
|
UTF-8
| 732 | 3.75 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"sort"
)
type mySort struct {
ints []int
}
func (s *mySort) Len() int { return len(s.ints) }
func (s *mySort) Swap(i, j int) { s.ints[i], s.ints[j] = s.ints[j], s.ints[i] }
func (s *mySort) Less(i, j int) bool { return s.ints[i] < s.ints[j] }
func isParindrome(s sort.Interface) bool {
for i := 0; i < s.Len()/2; i++ {
if !(!s.Less(i, s.Len()-1-i) && !s.Less(s.Len()-i-1, i)) {
return false
}
}
return true
}
func main() {
ints1 := []int{1, 2, 3, 3, 2, 1}
fmt.Println(isParindrome(&mySort{ints: ints1}))
ints2 := []int{1, 2, 3, 2, 1}
fmt.Println(isParindrome(&mySort{ints: ints2}))
ints3 := []int{1, 2, 3, 4, 5}
fmt.Println(isParindrome(&mySort{ints: ints3}))
}
| true |
be2bbb858b39530e8e89b83654f6bb47169803c8
|
Go
|
aclements/go-misc
|
/findflakes/flaketest.go
|
UTF-8
| 6,617 | 2.890625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io"
"log"
)
type FlakeTestResult struct {
All []FlakeRegion
}
type FlakeRegion struct {
// Times gives the times of all failures in this region, in
// increasing order.
//
// TODO: Remove some of the redundant fields?
Times []int
// First and Last are the indexes of the first and last
// failures in this flaky region. These are equivalent to
// Times[0] and Times[len(Times)-1], respectively.
First, Last int
// Failures is the number of failures in the region. This is
// equivalent to len(Times).
Failures int
// FailureProbability is the fraction of builds in this region
// that failed.
FailureProbability float64
// GoodnessOfFit is the goodness of fit test for this region
// against the maximum likelihood estimate geometric
// distribution for these failures. This is primarily for
// debugging.
GoodnessOfFit *AndersonDarlingTestResult
}
// FlakeTest finds ranges of commits over which the failure
// probability of a test is fairly consistent. The failures argument
// gives the indexes of commits with failing tests.
//
// This works by assuming flaky tests are a Bernoulli process. That
// is, they fail with some probability and each failure is independent
// of other failures. Using this assumption, it subdivides the failure
// events to find subranges where the distribution of times between
// failures is very similar to a geometric distribution (determined
// using an Anderson-Darling goodness-of-fit test).
func FlakeTest(failures []int) *FlakeTestResult {
result := &FlakeTestResult{}
result.subdivide(failures)
return result
}
// subdivide adds events to the flake test result if it has a strongly
// geometric interarrival distribution. Otherwise, it recursively
// subdivides events on the longest gap.
//
// events must be strictly monotonically increasing.
func (r *FlakeTestResult) subdivide(events []int) {
if len(events) == 1 {
// Isolated failure.
region := FlakeRegion{events, events[0], events[0], 1, 1, nil}
r.All = append(r.All, region)
return
}
mle, ad := interarrivalAnalysis(events)
if ad == nil || ad.P >= 0.05 {
// We failed to reject the null hypothesis that this
// isn't geometrically distributed. That's about as
// close as we're going to get to calling it
// geometrically distributed.
region := FlakeRegion{events, events[0], events[len(events)-1], len(events), mle.P, ad}
r.All = append(r.All, region)
return
}
// We reject the null hypothesis and accept the alternate
// hypothesis that this range of events is not a Bernoulli
// process. Subdivide on the longest gap, which is the least
// likely event in this range.
longestIndex, longestVal := 0, events[1]-events[0]
for i := 0; i < len(events)-1; i++ {
val := events[i+1] - events[i]
if val > longestVal {
longestIndex, longestVal = i, val
}
}
//fmt.Fprintln(os.Stderr, "subdividing", events[:longestIndex+1], events[longestIndex+1:], mle.P, ad.P)
// Find the more recent ranges first.
r.subdivide(events[longestIndex+1:])
r.subdivide(events[:longestIndex+1])
}
// interarrivalAnalysis returns the maximum likelihood estimated
// distribution for the times between events and the Anderson-Darling
// test for how closely the data matches this distribution. ad will be
// nil if there is no time between any of the events.
//
// events must be strictly monotonically increasing.
func interarrivalAnalysis(events []int) (mle *GeometricDist, ad *AndersonDarlingTestResult) {
interarrivalTimes := make([]int, len(events)-1)
sum := 0
for i := 0; i < len(events)-1; i++ {
delta := events[i+1] - events[i] - 1
interarrivalTimes[i] = delta
sum += delta
}
// Compute maximum likelihood estimate of geometric
// distribution underlying interarrivalTimes.
mle = &GeometricDist{P: float64(len(interarrivalTimes)) / float64(len(interarrivalTimes)+sum)}
if mle.P == 1 {
// This happens if there are no gaps between events.
// In this case Anderson-Darling is undefined because
// the CDF is 1.
return
}
// Compute Anderson-Darling goodness-of-fit for the observed
// distribution against the theoretical distribution.
var err error
ad, err = AndersonDarlingTest(interarrivalTimes, mle)
if err != nil {
log.Fatal("Anderson-Darling test failed: ", err)
}
return
}
func (r *FlakeTestResult) Dump(w io.Writer) {
for i := range r.All {
reg := &r.All[len(r.All)-i-1]
gof := 0.0
if reg.GoodnessOfFit != nil {
gof = reg.GoodnessOfFit.P
}
fmt.Fprintln(w, reg.First, 0, 0)
fmt.Fprintln(w, reg.First, reg.FailureProbability, gof)
fmt.Fprintln(w, reg.Last, reg.FailureProbability, gof)
fmt.Fprintln(w, reg.Last, 0, 0)
}
}
// StillHappening returns the probability that the flake is still
// happening as of time t.
func (r *FlakeRegion) StillHappening(t int) float64 {
if t < r.First {
return 0
}
dist := GeometricDist{P: r.FailureProbability, Start: r.Last + 1}
return 1 - dist.CDF(t)
}
// Bounds returns the time at which the probability that the failure
// started rises above p and the time at which the probability that
// the failure stopped falls below p. Note that this has no idea of
// the "current" time, so stop may be "in the future."
func (r *FlakeRegion) Bounds(p float64) (start, stop int) {
dist := GeometricDist{P: r.FailureProbability}
delta := dist.InvCDF(1 - p)
return r.First - delta, r.Last + delta
}
// StartedAtOrBefore returns the probability that the failure start at
// or before time t.
func (r *FlakeRegion) StartedAtOrBefore(t int) float64 {
if t > r.First {
return 1
}
dist := GeometricDist{P: r.FailureProbability}
return 1 - dist.CDF(r.First-t-1)
}
func (r *FlakeRegion) StartedAt(t int) float64 {
dist := GeometricDist{P: r.FailureProbability}
return dist.PMF(r.First - t)
}
// Culprit gives the probability P that the event at time T was
// responsible for a failure.
type Culprit struct {
P float64
T int
}
// Culprits returns the possible culprits for this failure up to a
// cumulative probability of cumProb or at most limit events. Culprits
// are returned in reverse time order (from most likely culprit to
// least likely).
func (r *FlakeRegion) Culprits(cumProb float64, limit int) []Culprit {
culprits := []Culprit{}
total := 0.0
for t := r.First; t >= 0 && t > r.First-limit; t-- {
p := r.StartedAt(t)
culprits = append(culprits, Culprit{P: p, T: t})
total += p
if total > cumProb {
break
}
}
return culprits
}
| true |
f9b2efeabd961a589391b8937a5283340c7f91f1
|
Go
|
bayek0fsiwa/Practice-Programs
|
/go/factorial.go
|
UTF-8
| 134 | 3.25 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
func factorial(5) int {
fact := 1
for i:= 0; i <= num; i++{
fact += fact *i
}
fmt.Println("factorial is", fact)
}
| true |
9e265030ff84ff66c4a4b2aabdac052c16b8668e
|
Go
|
itfantasy/gonode-toolkit
|
/toolkit/gen_mmo/boundingbox.go
|
UTF-8
| 1,785 | 3.0625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package gen_mmo
import (
"errors"
)
type BoundingBox struct {
max *Vector
min *Vector
}
func NewBoundingBox(min, max *Vector) *BoundingBox {
b := new(BoundingBox)
b.min = min
b.max = max
return b
}
func NewBoundingBoxFromPoints(points ...*Vector) (*BoundingBox, error) {
if points == nil {
return nil, errors.New("the points can not be nil!")
}
if len(points) <= 0 {
return nil, errors.New("the points' len can not be zero!")
}
min := points[0]
max := points[1]
for _, point := range points {
min = VMin(min, point)
max = VMax(max, point)
}
return NewBoundingBox(min, max), nil
}
func (b *BoundingBox) Max() *Vector {
return b.max
}
func (b *BoundingBox) Min() *Vector {
return b.min
}
func (b *BoundingBox) SetMax(max *Vector) {
b.max = max
}
func (b *BoundingBox) SetMin(min *Vector) {
b.min = min
}
func (b *BoundingBox) Size() *Vector {
return VSubtract(b.Max(), b.Min())
}
func (b *BoundingBox) Contains(point *Vector) bool {
return (point.X() < b.Min().X() || point.X() > b.Max().X() ||
point.Y() < b.Min().Y() || point.Y() > b.Max().Y() ||
point.Z() < b.Min().Z() || point.Z() > b.Max().Z()) == false
}
func (b *BoundingBox) Contains2d(point *Vector) bool {
return (point.X() < b.Min().X() || point.X() > b.Max().X() ||
point.Y() < b.Min().Y() || point.Y() > b.Max().Y()) == false
}
func (b *BoundingBox) IntersectWith(other *BoundingBox) *BoundingBox {
return NewBoundingBox(VMax(b.Min(), other.Min()), VMin(b.Max(), other.Max()))
}
func (b *BoundingBox) UnionWith(other *BoundingBox) *BoundingBox {
return NewBoundingBox(VMin(b.Min(), other.Min()), VMax(b.Max(), other.Max()))
}
func (b *BoundingBox) IsValid() bool {
return (b.Max().X() < b.Min().X() || b.Max().Y() < b.Min().Y() || b.Max().Z() < b.Min().Z()) == false
}
| true |
9cbdced33db0eff625299aacd368c9d6a6587c77
|
Go
|
finbourne/oidc-ingress
|
/pkg/handlers/redis-state_test.go
|
UTF-8
| 1,448 | 2.71875 | 3 |
[] |
no_license
|
[] |
no_license
|
package handlers
import (
"strings"
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/go-redis/redis/v7"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func TestSaveRedirectURIForClient(t *testing.T) {
logger := logrus.New()
mr, err := miniredis.Run()
if err != nil {
panic(err)
}
defer mr.Close()
ss := NewRedisStateStorer(mr.Addr(), logger)
ss.SaveRedirectURIForClient("testClient", "https://boo.finbourne.com")
list := mr.Keys()
assert.Equal(t, 1, len(list))
value, _ := mr.Get(list[0])
assert.Equal(t, "testClient|https://boo.finbourne.com", value)
}
func TestGetRedirectURI(t *testing.T) {
logger := logrus.New()
mr, err := miniredis.Run()
if err != nil {
panic(err)
}
defer mr.Close()
ss := NewRedisStateStorer(mr.Addr(), logger)
ss.SaveRedirectURIForClient("testClient", "https://boo.finbourne.com")
list := mr.Keys()
assert.Equal(t, 1, len(list))
value1, value2, _ := ss.GetRedirectURI(strings.Split(list[0], "/")[2])
assert.Equal(t, "testClient", value1)
assert.Equal(t, "https://boo.finbourne.com", value2)
}
func TestGetRedirectURIFailsIfNotPresent(t *testing.T) {
logger := logrus.New()
mr, err := miniredis.Run()
if err != nil {
panic(err)
}
defer mr.Close()
ss := NewRedisStateStorer(mr.Addr(), logger)
value1, value2, err := ss.GetRedirectURI("token1234")
assert.Equal(t, "", value1)
assert.Equal(t, "", value2)
assert.Equal(t, redis.Nil, err)
}
| true |
ba7d3a18706c183d5bd22d310452a0c4bcd7145b
|
Go
|
srivastava-yash/golang-redis-mock
|
/storage/generic_map_test.go
|
UTF-8
| 3,429 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package storage
import (
"runtime"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestConcurrentMapSingleClientStoreAndLoad(t *testing.T) {
m := NewGenericConcurrentMap()
m.Store("foo", "bar")
m.Store("foo2", "2")
val, ok := m.Load("foo")
assert.Equal(t, ok, true)
assert.Equal(t, val, "bar")
val, ok = m.Load("foo2")
assert.Equal(t, val, "2")
_, ok = m.Load("foo3")
assert.Equal(t, ok, false)
}
func TestConcurrentSingleClientMapDelete(t *testing.T) {
m := NewGenericConcurrentMap()
m.Store("foo", "bar")
m.Store("foo2", "2")
ok := m.Delete("foo")
assert.Equal(t, ok, true)
ok = m.Delete("foo2")
assert.Equal(t, ok, true)
ok = m.Delete("foo3")
assert.Equal(t, ok, false)
}
func reader(t *testing.T, g *GenericConcurrentMap, c chan string, key string) {
v, _ := g.Load(key)
c <- v
}
func writer(g *GenericConcurrentMap, c chan string, key string, value string) {
g.Store(key, value)
c <- value
}
func TestConcurrentMapAccessMultipleClients(t *testing.T) {
runtime.GOMAXPROCS(4)
// Single writer, 2 readers
// Ideas for this test are taken from https://golang.org/src/runtime/rwmutex_test.go
m := NewGenericConcurrentMap()
// Store initial value
m.Store("foo", "omg")
c := make(chan string, 1)
done := make(chan string)
// Enforce sequential access via channels
go reader(t, m, c, "foo")
assert.Equal(t, <-c, "omg")
go reader(t, m, c, "foo")
assert.Equal(t, <-c, "omg")
go writer(m, done, "foo", "lol")
<-done
go reader(t, m, c, "foo")
assert.Equal(t, <-c, "lol")
go reader(t, m, c, "foo")
assert.Equal(t, <-c, "lol")
// Try concurrent reads without waiting, but waiting only on write
m.Store("foo", "lol")
go reader(t, m, c, "foo")
go reader(t, m, c, "foo")
go writer(m, done, "foo", "lol2")
go reader(t, m, c, "foo")
<-done
go reader(t, m, c, "foo")
for i := 0; i < 3; i++ {
val := <-c
assert.Equal(t, val, "lol")
}
assert.Equal(t, <-c, "lol2")
}
func TestConcurrentMapWriteMultipleWriters(t *testing.T) {
m := NewGenericConcurrentMap()
done := make(chan string)
c := make(chan string, 1)
// We need this variable to hold the first value that is written. Because goroutines
// can run concurrently, we don't know which write will succeed. By storing the return
// value from write, we know which value to compare against
var curr string
// Two concurrent writers. Any may win first because we are only waiting for one
go writer(m, done, "foo", "lol")
go writer(m, done, "foo", "lol2")
curr = <-done
go reader(t, m, c, "foo")
assert.Equal(t, <-c, curr)
// If we now assert a reader, we may get lol or lol2, because we are not waiting on done.
// We have no way of knowing which one without the wait
curr = <-done
go reader(t, m, c, "foo")
assert.Equal(t, <-c, curr)
}
func TestConcurrentMapWriteAndDelete(t *testing.T) {
m := NewGenericConcurrentMap()
var wg sync.WaitGroup
wg.Add(1)
// If we schedule one after each other, it may fail.
// There is no guarantee that write will finish first
// Here we use a waitgroup to wait for counter to go to zero
// Run write first
go func() {
m.Store("foo", "2")
wg.Done()
}()
go func() {
wg.Wait()
// Waitgroup counter is now zero
ok := m.Delete("foo")
assert.Equal(t, ok, true)
}()
wg.Add(1)
// Now run delete first
go func() {
wg.Wait()
m.Store("foo", "2")
}()
go func() {
ok := m.Delete("foo")
assert.Equal(t, ok, false)
wg.Done()
}()
}
| true |
09002d9e4cf3cb5c77f6fed86d1501959a6b3c04
|
Go
|
xiaobing94/dorm
|
/field.go
|
UTF-8
| 2,345 | 2.984375 | 3 |
[] |
no_license
|
[] |
no_license
|
package dorm
import (
"errors"
"fmt"
"reflect"
"strings"
"sync"
)
type StructField struct {
Name string
Tag reflect.StructTag
TagSettings map[string]string
Struct reflect.StructField
tagSettingsLock sync.RWMutex
}
// TagSettingsSet
func (sf *StructField) TagSettingsSet(key, val string) {
sf.tagSettingsLock.Lock()
defer sf.tagSettingsLock.Unlock()
sf.TagSettings[key] = val
}
// TagSettingsGet
func (sf *StructField) TagSettingsGet(key string) (string, bool) {
sf.tagSettingsLock.RLock()
defer sf.tagSettingsLock.RUnlock()
val, ok := sf.TagSettings[key]
return val, ok
}
// TagSettingsDelete
func (sf *StructField) TagSettingsDelete(key string) {
sf.tagSettingsLock.Lock()
defer sf.tagSettingsLock.Unlock()
delete(sf.TagSettings, key)
}
type Field struct {
*StructField
Field reflect.Value
}
// Set set a value to the field
func (field *Field) Set(value interface{}) (err error) {
if !field.Field.IsValid() {
return errors.New("field value not valid")
}
if !field.Field.CanAddr() {
return ErrUnaddressable
}
reflectValue, ok := value.(reflect.Value)
if !ok {
reflectValue = reflect.ValueOf(value)
}
fieldValue := field.Field
if reflectValue.IsValid() {
if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {
fieldValue.Set(reflectValue.Convert(fieldValue.Type()))
} else {
if fieldValue.Kind() == reflect.Ptr {
if fieldValue.IsNil() {
fieldValue.Set(reflect.New(field.Struct.Type.Elem()))
}
fieldValue = fieldValue.Elem()
}
if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {
fieldValue.Set(reflectValue.Convert(fieldValue.Type()))
} else {
err = fmt.Errorf("could not convert argument of field %s from %s to %s", field.Name, reflectValue.Type(), fieldValue.Type())
}
}
} else {
field.Field.Set(reflect.Zero(field.Field.Type()))
}
return err
}
func parseTagSetting(tags reflect.StructTag) map[string]string {
setting := map[string]string{}
for _, str := range []string{tags.Get("dorm")} {
if str == "" {
continue
}
tags := strings.Split(str, ";")
for _, value := range tags {
v := strings.Split(value, ":")
k := strings.TrimSpace(strings.ToUpper(v[0]))
if len(v) >= 2 {
setting[k] = strings.Join(v[1:], ":")
} else {
setting[k] = k
}
}
}
return setting
}
| true |
384e73eba7b7615b09328b28341ead2a7249a6e5
|
Go
|
kyledharrington/dynatrace-operator
|
/src/controllers/dynakube/activegate/internal/statefulset/builder/builder_test.go
|
UTF-8
| 2,179 | 3.0625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package builder
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
)
type ModifierMock struct {
mock.Mock
}
func NewModifierMock() *ModifierMock {
return &ModifierMock{}
}
func (m *ModifierMock) Enabled() bool {
args := m.Called()
return args.Bool(0)
}
func (m *ModifierMock) Modify(sts *appsv1.StatefulSet) error {
args := m.Called(sts)
return args.Error(0)
}
func TestBuilder(t *testing.T) {
t.Run("Simple, no modifiers", func(t *testing.T) {
b := Builder{}
actual, err := b.Build()
assert.NoError(t, err)
expected := appsv1.StatefulSet{}
assert.Equal(t, expected, actual)
})
t.Run("One modifier", func(t *testing.T) {
b := Builder{}
modifierMock := NewModifierMock()
modifierMock.On("Modify", mock.Anything).Return(nil)
modifierMock.On("Enabled").Return(true)
actual, err := b.AddModifier(modifierMock).Build()
require.NoError(t, err)
modifierMock.AssertNumberOfCalls(t, "Modify", 1)
expected := appsv1.StatefulSet{}
assert.Equal(t, expected, actual)
})
t.Run("One modifier, not enabled", func(t *testing.T) {
b := Builder{}
modifierMock := NewModifierMock()
modifierMock.On("Modify", mock.Anything).Return(nil)
modifierMock.On("Enabled").Return(false)
actual, err := b.AddModifier(modifierMock).Build()
require.NoError(t, err)
modifierMock.AssertNumberOfCalls(t, "Modify", 0)
expected := appsv1.StatefulSet{}
assert.Equal(t, expected, actual)
})
t.Run("Two modifiers, one used twice", func(t *testing.T) {
b := Builder{}
modifierMock0 := NewModifierMock()
modifierMock0.On("Enabled").Return(true)
modifierMock0.On("Modify", mock.Anything).Return(nil)
modifierMock1 := NewModifierMock()
modifierMock1.On("Enabled").Return(true)
modifierMock1.On("Modify", mock.Anything).Return(nil)
actual, err := b.AddModifier(modifierMock0, modifierMock0, modifierMock1).Build()
require.NoError(t, err)
modifierMock0.AssertNumberOfCalls(t, "Modify", 2)
modifierMock1.AssertNumberOfCalls(t, "Modify", 1)
expected := appsv1.StatefulSet{}
assert.Equal(t, expected, actual)
})
}
| true |
7f08ceb0078f6272292198f25dd47772bb3f751f
|
Go
|
rprajapati0067/golang-coding-practice
|
/pointers/main.go
|
UTF-8
| 863 | 3.8125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"errors"
"fmt"
)
type User struct {
Status string
}
func (u *User) UpdateStatus(status string) {
u.Status = status
}
func updateUser(user *User, status string) {
user.Status = status
}
func getUser(userId int64) (*User, error) {
if userId <= 0 {
return nil, errors.New("user not found")
}
user := User{}
return &user, nil
}
func main() {
user := User{Status: "active"}
fmt.Println(user.Status)
//user.UpdateStatus("inactive")
updateUser(&user, "inactive")
fmt.Println(user.Status)
currentUser, userErrr := getUser(1)
if userErrr != nil {
return
}
fmt.Println(currentUser)
/*var name = "ravi"
var namePointer = &name // this will give memory address of name variable
fmt.Println(*namePointer) // give me the value this pointer is pointing to(dereference operator gives actual value)
fmt.Println(&name)*/
}
| true |
75be299727f879a33e5be21de9329118210a06c3
|
Go
|
scottcagno/tree
|
/tmp/tree.go
|
UTF-8
| 770 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
// *
// * Copyright 2014, Scott Cagno, All rights reserved.
// * BSD Licensed - sites.google.com/site/bsdc3license
// *
// * B+Tree Implementation
// *
package tree
import (
"bytes"
)
// tree
type Tree struct {
deg int
root *Node
}
// initialize tree
func InitTree(deg int) *Tree {
return &Tree{
deg: deg,
root: &Node{
make([]Idx, 0),
make([]Dat, 0),
},
}
}
// search for a record with search-key value k
func (self *Tree) Search(k []byte) *Node {
if self.root.IsLeaf() {
return &self.root
}
// drill down...
return nil
}
// insert
func (self *Tree) Insert(k, v []byte) bool {
return false
}
// return
func (self *Tree) Return(k []byte) ([]byte, bool) {
return nil, false
}
// delete
func (self *Tree) Delete(k []byte) bool {
return false
}
| true |
27fea84fd75f9dc36a93ab29662fa5047eba7ba3
|
Go
|
rdmueller/aoc-2018
|
/day12/go/anoff/src/setup_test.go
|
UTF-8
| 1,434 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"testing"
)
func TestReadInpupt(t *testing.T) {
s := readInput("../test.txt")
exp := 16
if len(s) != exp {
t.Errorf("Invalid length of lines parsed, expected:%d but got:%d", len(s), exp)
}
}
func TestExtractPots(t *testing.T) {
pots := extractPots(".#..###..")
exp := []bool{false, true, false, false, true, true, true, false, false}
if pots.Len() != len(exp) {
t.Errorf("Incorrect number of pots, expected:%d but got:%d", len(exp), pots.Len())
}
ix := 0
for i := pots.Front(); i.Next() != nil; i = i.Next() {
p := i.Value.(*Pot)
if p.hasPlant != exp[ix] {
t.Errorf("Incorrect hasPlant property for pot:%d, expected:%t but got:%t", i, exp[ix], p.hasPlant)
}
ix++
}
}
func TestExtractPropagationRules(t *testing.T) {
in := []string{"...## => #","..#.. => #"}
exp := []PropRule{
{id: 0, pattern: [5]bool{false, false, false, true, true}, result: true},
{id: 1, pattern: [5]bool{false, false, true, false, false}, result: true},
}
rules := extractPropagationRules(in)
for i, p := range rules {
if p.id != exp[i].id {
t.Errorf("Incorrect id, expected:%d, got:%d", exp[i].id, p.id)
}
if p.pattern != exp[i].pattern {
t.Errorf("Wrong propagation pattern for input:%d, expected:%t, got:%t", i, exp[i].pattern, p.pattern)
}
if p.result != exp[i].result {
t.Errorf("Wrong propagation result for input:%d, expected:%t, got:%t", i, exp[i].result, p.result)
}
}
}
| true |
8801724112fe090fdfdcaec66cbdbb7e2219b37e
|
Go
|
gonearewe/go-music
|
/panel/render.go
|
UTF-8
| 1,046 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package panel
import (
"bufio"
"math/rand"
"strings"
. "github.com/fatih/color"
)
type ColorTheme [2]Attribute
var (
Spring = [2]Attribute{FgHiGreen /* */, FgGreen}
Autumn = [2]Attribute{FgHiYellow /* */, FgYellow}
Winter = [2]Attribute{FgHiBlue /* */, FgBlue}
Rose = [2]Attribute{FgHiRed /* */, FgHiMagenta}
Valentine = [2]Attribute{FgHiMagenta /**/, FgMagenta}
)
// RenderText rendering given text so that it looks colorful on the screen.
func RenderText(text string, theme ColorTheme) string {
var flag bool
s := make([]string, 5)
scanner := bufio.NewScanner(strings.NewReader(text))
for scanner.Scan() {
if flag {
s = append(s, New(theme[1]).Sprintln(scanner.Text()))
} else {
s = append(s, New(theme[0]).Sprintln(scanner.Text()))
}
flag = !flag
}
return strings.Join(s, "")
}
// RandomColorTheme returns a random ColorTheme.
func RandomColorTheme() ColorTheme {
var themes = []ColorTheme{
Spring, Autumn, Winter,
Rose, Valentine,
}
return themes[rand.Intn(len(themes))]
}
| true |
c23709911cf91711dcc351e99c98ed9580c05651
|
Go
|
mailru/easyjson
|
/tests/data.go
|
UTF-8
| 16,943 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package tests
import (
"fmt"
"math"
"net"
"time"
"github.com/mailru/easyjson"
"github.com/mailru/easyjson/opt"
)
type PrimitiveTypes struct {
String string
Bool bool
Int int
Int8 int8
Int16 int16
Int32 int32
Int64 int64
Uint uint
Uint8 uint8
Uint16 uint16
Uint32 uint32
Uint64 uint64
IntString int `json:",string"`
Int8String int8 `json:",string"`
Int16String int16 `json:",string"`
Int32String int32 `json:",string"`
Int64String int64 `json:",string"`
UintString uint `json:",string"`
Uint8String uint8 `json:",string"`
Uint16String uint16 `json:",string"`
Uint32String uint32 `json:",string"`
Uint64String uint64 `json:",string"`
Float32 float32
Float64 float64
Float32String float32 `json:",string"`
Float64String float64 `json:",string"`
Ptr *string
PtrNil *string
}
var str = "bla"
var primitiveTypesValue = PrimitiveTypes{
String: "test", Bool: true,
Int: math.MinInt32,
Int8: math.MinInt8,
Int16: math.MinInt16,
Int32: math.MinInt32,
Int64: math.MinInt64,
Uint: math.MaxUint32,
Uint8: math.MaxUint8,
Uint16: math.MaxUint16,
Uint32: math.MaxUint32,
Uint64: math.MaxUint64,
IntString: math.MinInt32,
Int8String: math.MinInt8,
Int16String: math.MinInt16,
Int32String: math.MinInt32,
Int64String: math.MinInt64,
UintString: math.MaxUint32,
Uint8String: math.MaxUint8,
Uint16String: math.MaxUint16,
Uint32String: math.MaxUint32,
Uint64String: math.MaxUint64,
Float32: 1.5,
Float64: math.MaxFloat64,
Float32String: 1.5,
Float64String: math.MaxFloat64,
Ptr: &str,
}
var primitiveTypesString = "{" +
`"String":"test","Bool":true,` +
`"Int":` + fmt.Sprint(math.MinInt32) + `,` +
`"Int8":` + fmt.Sprint(math.MinInt8) + `,` +
`"Int16":` + fmt.Sprint(math.MinInt16) + `,` +
`"Int32":` + fmt.Sprint(math.MinInt32) + `,` +
`"Int64":` + fmt.Sprint(int64(math.MinInt64)) + `,` +
`"Uint":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` +
`"Uint8":` + fmt.Sprint(math.MaxUint8) + `,` +
`"Uint16":` + fmt.Sprint(math.MaxUint16) + `,` +
`"Uint32":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` +
`"Uint64":` + fmt.Sprint(uint64(math.MaxUint64)) + `,` +
`"IntString":"` + fmt.Sprint(math.MinInt32) + `",` +
`"Int8String":"` + fmt.Sprint(math.MinInt8) + `",` +
`"Int16String":"` + fmt.Sprint(math.MinInt16) + `",` +
`"Int32String":"` + fmt.Sprint(math.MinInt32) + `",` +
`"Int64String":"` + fmt.Sprint(int64(math.MinInt64)) + `",` +
`"UintString":"` + fmt.Sprint(uint32(math.MaxUint32)) + `",` +
`"Uint8String":"` + fmt.Sprint(math.MaxUint8) + `",` +
`"Uint16String":"` + fmt.Sprint(math.MaxUint16) + `",` +
`"Uint32String":"` + fmt.Sprint(uint32(math.MaxUint32)) + `",` +
`"Uint64String":"` + fmt.Sprint(uint64(math.MaxUint64)) + `",` +
`"Float32":` + fmt.Sprint(1.5) + `,` +
`"Float64":` + fmt.Sprint(math.MaxFloat64) + `,` +
`"Float32String":"` + fmt.Sprint(1.5) + `",` +
`"Float64String":"` + fmt.Sprint(math.MaxFloat64) + `",` +
`"Ptr":"bla",` +
`"PtrNil":null` +
"}"
type (
NamedString string
NamedBool bool
NamedInt int
NamedInt8 int8
NamedInt16 int16
NamedInt32 int32
NamedInt64 int64
NamedUint uint
NamedUint8 uint8
NamedUint16 uint16
NamedUint32 uint32
NamedUint64 uint64
NamedFloat32 float32
NamedFloat64 float64
NamedStrPtr *string
)
type NamedPrimitiveTypes struct {
String NamedString
Bool NamedBool
Int NamedInt
Int8 NamedInt8
Int16 NamedInt16
Int32 NamedInt32
Int64 NamedInt64
Uint NamedUint
Uint8 NamedUint8
Uint16 NamedUint16
Uint32 NamedUint32
Uint64 NamedUint64
Float32 NamedFloat32
Float64 NamedFloat64
Ptr NamedStrPtr
PtrNil NamedStrPtr
}
var namedPrimitiveTypesValue = NamedPrimitiveTypes{
String: "test",
Bool: true,
Int: math.MinInt32,
Int8: math.MinInt8,
Int16: math.MinInt16,
Int32: math.MinInt32,
Int64: math.MinInt64,
Uint: math.MaxUint32,
Uint8: math.MaxUint8,
Uint16: math.MaxUint16,
Uint32: math.MaxUint32,
Uint64: math.MaxUint64,
Float32: 1.5,
Float64: math.MaxFloat64,
Ptr: NamedStrPtr(&str),
}
var namedPrimitiveTypesString = "{" +
`"String":"test",` +
`"Bool":true,` +
`"Int":` + fmt.Sprint(math.MinInt32) + `,` +
`"Int8":` + fmt.Sprint(math.MinInt8) + `,` +
`"Int16":` + fmt.Sprint(math.MinInt16) + `,` +
`"Int32":` + fmt.Sprint(math.MinInt32) + `,` +
`"Int64":` + fmt.Sprint(int64(math.MinInt64)) + `,` +
`"Uint":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` +
`"Uint8":` + fmt.Sprint(math.MaxUint8) + `,` +
`"Uint16":` + fmt.Sprint(math.MaxUint16) + `,` +
`"Uint32":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` +
`"Uint64":` + fmt.Sprint(uint64(math.MaxUint64)) + `,` +
`"Float32":` + fmt.Sprint(1.5) + `,` +
`"Float64":` + fmt.Sprint(math.MaxFloat64) + `,` +
`"Ptr":"bla",` +
`"PtrNil":null` +
"}"
type SubStruct struct {
Value string
Value2 string
unexpored bool
}
type SubP struct {
V string
}
type SubStructAlias SubStruct
type Structs struct {
SubStruct
*SubP
Value2 int
Sub1 SubStruct `json:"substruct"`
Sub2 *SubStruct
SubNil *SubStruct
SubSlice []SubStruct
SubSliceNil []SubStruct
SubPtrSlice []*SubStruct
SubPtrSliceNil []*SubStruct
SubA1 SubStructAlias
SubA2 *SubStructAlias
Anonymous struct {
V string
I int
}
Anonymous1 *struct {
V string
}
AnonymousSlice []struct{ V int }
AnonymousPtrSlice []*struct{ V int }
Slice []string
unexported bool
}
var structsValue = Structs{
SubStruct: SubStruct{Value: "test"},
SubP: &SubP{V: "subp"},
Value2: 5,
Sub1: SubStruct{Value: "test1", Value2: "v"},
Sub2: &SubStruct{Value: "test2", Value2: "v2"},
SubSlice: []SubStruct{
{Value: "s1"},
{Value: "s2"},
},
SubPtrSlice: []*SubStruct{
{Value: "p1"},
{Value: "p2"},
},
SubA1: SubStructAlias{Value: "test3", Value2: "v3"},
SubA2: &SubStructAlias{Value: "test4", Value2: "v4"},
Anonymous: struct {
V string
I int
}{V: "bla", I: 5},
Anonymous1: &struct {
V string
}{V: "bla1"},
AnonymousSlice: []struct{ V int }{{1}, {2}},
AnonymousPtrSlice: []*struct{ V int }{{3}, {4}},
Slice: []string{"test5", "test6"},
}
var structsString = "{" +
`"Value2":5,` +
`"substruct":{"Value":"test1","Value2":"v"},` +
`"Sub2":{"Value":"test2","Value2":"v2"},` +
`"SubNil":null,` +
`"SubSlice":[{"Value":"s1","Value2":""},{"Value":"s2","Value2":""}],` +
`"SubSliceNil":null,` +
`"SubPtrSlice":[{"Value":"p1","Value2":""},{"Value":"p2","Value2":""}],` +
`"SubPtrSliceNil":null,` +
`"SubA1":{"Value":"test3","Value2":"v3"},` +
`"SubA2":{"Value":"test4","Value2":"v4"},` +
`"Anonymous":{"V":"bla","I":5},` +
`"Anonymous1":{"V":"bla1"},` +
`"AnonymousSlice":[{"V":1},{"V":2}],` +
`"AnonymousPtrSlice":[{"V":3},{"V":4}],` +
`"Slice":["test5","test6"],` +
// Embedded fields go last.
`"V":"subp",` +
`"Value":"test"` +
"}"
type OmitEmpty struct {
// NOTE: first field is empty to test comma printing.
StrE, StrNE string `json:",omitempty"`
PtrE, PtrNE *string `json:",omitempty"`
IntNE int `json:"intField,omitempty"`
IntE int `json:",omitempty"`
// NOTE: omitempty has no effect on non-pointer struct fields.
SubE, SubNE SubStruct `json:",omitempty"`
SubPE, SubPNE *SubStruct `json:",omitempty"`
}
var omitEmptyValue = OmitEmpty{
StrNE: "str",
PtrNE: &str,
IntNE: 6,
SubNE: SubStruct{Value: "1", Value2: "2"},
SubPNE: &SubStruct{Value: "3", Value2: "4"},
}
var omitEmptyString = "{" +
`"StrNE":"str",` +
`"PtrNE":"bla",` +
`"intField":6,` +
`"SubE":{"Value":"","Value2":""},` +
`"SubNE":{"Value":"1","Value2":"2"},` +
`"SubPNE":{"Value":"3","Value2":"4"}` +
"}"
type Opts struct {
StrNull opt.String
StrEmpty opt.String
Str opt.String
StrOmitempty opt.String `json:",omitempty"`
IntNull opt.Int
IntZero opt.Int
Int opt.Int
}
var optsValue = Opts{
StrEmpty: opt.OString(""),
Str: opt.OString("test"),
IntZero: opt.OInt(0),
Int: opt.OInt(5),
}
var optsString = `{` +
`"StrNull":null,` +
`"StrEmpty":"",` +
`"Str":"test",` +
`"IntNull":null,` +
`"IntZero":0,` +
`"Int":5` +
`}`
type Raw struct {
Field easyjson.RawMessage
Field2 string
}
var rawValue = Raw{
Field: []byte(`{"a" : "b"}`),
Field2: "test",
}
var rawString = `{` +
`"Field":{"a" : "b"},` +
`"Field2":"test"` +
`}`
type StdMarshaler struct {
T time.Time
IP net.IP
}
var stdMarshalerValue = StdMarshaler{
T: time.Date(2016, 01, 02, 14, 15, 10, 0, time.UTC),
IP: net.IPv4(192, 168, 0, 1),
}
var stdMarshalerString = `{` +
`"T":"2016-01-02T14:15:10Z",` +
`"IP":"192.168.0.1"` +
`}`
type UserMarshaler struct {
V vMarshaler
T tMarshaler
}
type vMarshaler net.IP
func (v vMarshaler) MarshalJSON() ([]byte, error) {
return []byte(`"0::0"`), nil
}
func (v *vMarshaler) UnmarshalJSON([]byte) error {
*v = vMarshaler(net.IPv6zero)
return nil
}
type tMarshaler net.IP
func (v tMarshaler) MarshalText() ([]byte, error) {
return []byte(`[0::0]`), nil
}
func (v *tMarshaler) UnmarshalText([]byte) error {
*v = tMarshaler(net.IPv6zero)
return nil
}
var userMarshalerValue = UserMarshaler{
V: vMarshaler(net.IPv6zero),
T: tMarshaler(net.IPv6zero),
}
var userMarshalerString = `{` +
`"V":"0::0",` +
`"T":"[0::0]"` +
`}`
type unexportedStruct struct {
Value string
}
var unexportedStructValue = unexportedStruct{"test"}
var unexportedStructString = `{"Value":"test"}`
type ExcludedField struct {
Process bool `json:"process"`
DoNotProcess bool `json:"-"`
DoNotProcess1 bool `json:"-"`
}
var excludedFieldValue = ExcludedField{
Process: true,
DoNotProcess: false,
DoNotProcess1: false,
}
var excludedFieldString = `{"process":true}`
type Slices struct {
ByteSlice []byte
EmptyByteSlice []byte
NilByteSlice []byte
IntSlice []int
EmptyIntSlice []int
NilIntSlice []int
}
var sliceValue = Slices{
ByteSlice: []byte("abc"),
EmptyByteSlice: []byte{},
NilByteSlice: []byte(nil),
IntSlice: []int{1, 2, 3, 4, 5},
EmptyIntSlice: []int{},
NilIntSlice: []int(nil),
}
var sliceString = `{` +
`"ByteSlice":"YWJj",` +
`"EmptyByteSlice":"",` +
`"NilByteSlice":null,` +
`"IntSlice":[1,2,3,4,5],` +
`"EmptyIntSlice":[],` +
`"NilIntSlice":null` +
`}`
type Arrays struct {
ByteArray [3]byte
EmptyByteArray [0]byte
IntArray [5]int
EmptyIntArray [0]int
}
var arrayValue = Arrays{
ByteArray: [3]byte{'a', 'b', 'c'},
EmptyByteArray: [0]byte{},
IntArray: [5]int{1, 2, 3, 4, 5},
EmptyIntArray: [0]int{},
}
var arrayString = `{` +
`"ByteArray":"YWJj",` +
`"EmptyByteArray":"",` +
`"IntArray":[1,2,3,4,5],` +
`"EmptyIntArray":[]` +
`}`
var arrayOverflowString = `{` +
`"ByteArray":"YWJjbnNk",` +
`"EmptyByteArray":"YWJj",` +
`"IntArray":[1,2,3,4,5,6],` +
`"EmptyIntArray":[7,8]` +
`}`
var arrayUnderflowValue = Arrays{
ByteArray: [3]byte{'x', 0, 0},
EmptyByteArray: [0]byte{},
IntArray: [5]int{1, 2, 0, 0, 0},
EmptyIntArray: [0]int{},
}
var arrayUnderflowString = `{` +
`"ByteArray":"eA==",` +
`"IntArray":[1,2]` +
`}`
type Str string
type Maps struct {
Map map[string]string
InterfaceMap map[string]interface{}
NilMap map[string]string
CustomMap map[Str]Str
}
var mapsValue = Maps{
Map: map[string]string{"A": "b"}, // only one item since map iteration is randomized
InterfaceMap: map[string]interface{}{"G": float64(1)},
CustomMap: map[Str]Str{"c": "d"},
}
var mapsString = `{` +
`"Map":{"A":"b"},` +
`"InterfaceMap":{"G":1},` +
`"NilMap":null,` +
`"CustomMap":{"c":"d"}` +
`}`
type NamedSlice []Str
type NamedMap map[Str]Str
type DeepNest struct {
SliceMap map[Str][]Str
SliceMap1 map[Str][]Str
SliceMap2 map[Str][]Str
NamedSliceMap map[Str]NamedSlice
NamedMapMap map[Str]NamedMap
MapSlice []map[Str]Str
NamedSliceSlice []NamedSlice
NamedMapSlice []NamedMap
NamedStringSlice []NamedString
}
var deepNestValue = DeepNest{
SliceMap: map[Str][]Str{
"testSliceMap": {
"0",
"1",
},
},
SliceMap1: map[Str][]Str{
"testSliceMap1": []Str(nil),
},
SliceMap2: map[Str][]Str{
"testSliceMap2": {},
},
NamedSliceMap: map[Str]NamedSlice{
"testNamedSliceMap": {
"2",
"3",
},
},
NamedMapMap: map[Str]NamedMap{
"testNamedMapMap": {
"key1": "value1",
},
},
MapSlice: []map[Str]Str{
{
"testMapSlice": "someValue",
},
},
NamedSliceSlice: []NamedSlice{
{
"someValue1",
"someValue2",
},
{
"someValue3",
"someValue4",
},
},
NamedMapSlice: []NamedMap{
{
"key2": "value2",
},
{
"key3": "value3",
},
},
NamedStringSlice: []NamedString{
"value4", "value5",
},
}
var deepNestString = `{` +
`"SliceMap":{` +
`"testSliceMap":["0","1"]` +
`},` +
`"SliceMap1":{` +
`"testSliceMap1":null` +
`},` +
`"SliceMap2":{` +
`"testSliceMap2":[]` +
`},` +
`"NamedSliceMap":{` +
`"testNamedSliceMap":["2","3"]` +
`},` +
`"NamedMapMap":{` +
`"testNamedMapMap":{"key1":"value1"}` +
`},` +
`"MapSlice":[` +
`{"testMapSlice":"someValue"}` +
`],` +
`"NamedSliceSlice":[` +
`["someValue1","someValue2"],` +
`["someValue3","someValue4"]` +
`],` +
`"NamedMapSlice":[` +
`{"key2":"value2"},` +
`{"key3":"value3"}` +
`],` +
`"NamedStringSlice":["value4","value5"]` +
`}`
type DeepNestOptional struct {
MapSlice []map[Str]Str `json:",omitempty"`
}
var deepNestOptionalValue = DeepNestOptional{
MapSlice: []map[Str]Str{{}},
}
var deepNestOptionalString = `{` +
`"MapSlice":[` +
`{}` +
`]` +
`}`
//easyjson:json
type Ints []int
var IntsValue = Ints{1, 2, 3, 4, 5}
var IntsString = `[1,2,3,4,5]`
//easyjson:json
type MapStringString map[string]string
var mapStringStringValue = MapStringString{"a": "b"}
var mapStringStringString = `{"a":"b"}`
type RequiredOptionalStruct struct {
FirstName string `json:"first_name,required"`
Lastname string `json:"last_name"`
}
type RequiredOptionalMap struct {
ReqMap map[int]string `json:"req_map,required"`
OmitEmptyMap map[int]string `json:"oe_map,omitempty"`
NoOmitEmptyMap map[int]string `json:"noe_map,!omitempty"`
}
//easyjson:json
type EncodingFlagsTestMap struct {
F map[string]string
}
//easyjson:json
type EncodingFlagsTestSlice struct {
F []string
}
type StructWithInterface struct {
Field1 int `json:"f1"`
Field2 interface{} `json:"f2"`
Field3 string `json:"f3"`
}
type EmbeddedStruct struct {
Field1 int `json:"f1"`
Field2 string `json:"f2"`
}
var structWithInterfaceString = `{"f1":1,"f2":{"f1":11,"f2":"22"},"f3":"3"}`
var structWithInterfaceValueFilled = StructWithInterface{1, &EmbeddedStruct{11, "22"}, "3"}
//easyjson:json
type MapIntString map[int]string
var mapIntStringValue = MapIntString{3: "hi"}
var mapIntStringValueString = `{"3":"hi"}`
//easyjson:json
type MapInt32String map[int32]string
var mapInt32StringValue = MapInt32String{-354634382: "life"}
var mapInt32StringValueString = `{"-354634382":"life"}`
//easyjson:json
type MapInt64String map[int64]string
var mapInt64StringValue = MapInt64String{-3546343826724305832: "life"}
var mapInt64StringValueString = `{"-3546343826724305832":"life"}`
//easyjson:json
type MapUintString map[uint]string
var mapUintStringValue = MapUintString{42: "life"}
var mapUintStringValueString = `{"42":"life"}`
//easyjson:json
type MapUint32String map[uint32]string
var mapUint32StringValue = MapUint32String{354634382: "life"}
var mapUint32StringValueString = `{"354634382":"life"}`
//easyjson:json
type MapUint64String map[uint64]string
var mapUint64StringValue = MapUint64String{3546343826724305832: "life"}
var mapUint64StringValueString = `{"3546343826724305832":"life"}`
//easyjson:json
type MapUintptrString map[uintptr]string
var mapUintptrStringValue = MapUintptrString{272679208: "obj"}
var mapUintptrStringValueString = `{"272679208":"obj"}`
type MyInt int
//easyjson:json
type MapMyIntString map[MyInt]string
var mapMyIntStringValue = MapMyIntString{MyInt(42): "life"}
var mapMyIntStringValueString = `{"42":"life"}`
//easyjson:json
type IntKeyedMapStruct struct {
Foo MapMyIntString `json:"foo"`
Bar map[int16]MapUint32String `json:"bar"`
}
var intKeyedMapStructValue = IntKeyedMapStruct{
Foo: mapMyIntStringValue,
Bar: map[int16]MapUint32String{32: mapUint32StringValue},
}
var intKeyedMapStructValueString = `{` +
`"foo":{"42":"life"},` +
`"bar":{"32":{"354634382":"life"}}` +
`}`
type IntArray [2]int
//easyjson:json
type IntArrayStruct struct {
Pointer *IntArray `json:"pointer"`
Value IntArray `json:"value"`
}
var intArrayStructValue = IntArrayStruct{
Pointer: &IntArray{1, 2},
Value: IntArray{1, 2},
}
var intArrayStructValueString = `{` +
`"pointer":[1,2],` +
`"value":[1,2]` +
`}`
type MyUInt8 uint8
//easyjson:json
type MyUInt8Slice []MyUInt8
var myUInt8SliceValue = MyUInt8Slice{1, 2, 3, 4, 5}
var myUInt8SliceString = `[1,2,3,4,5]`
//easyjson:json
type MyUInt8Array [2]MyUInt8
var myUInt8ArrayValue = MyUInt8Array{1, 2}
var myUInt8ArrayString = `[1,2]`
| true |
166d7014d73ba4edc0f4e88e5a72182d69d468b0
|
Go
|
julycw/goroutinepool
|
/request/request.go
|
UTF-8
| 1,253 | 2.953125 | 3 |
[] |
no_license
|
[] |
no_license
|
package request
import (
"errors"
"math/rand"
"time"
)
type ResultWork struct {
Request *RequestWork
Result interface{}
Error error
}
func (this *ResultWork) Init(request *RequestWork, result interface{}, err error) *ResultWork {
this.Request = request
this.Result = result
this.Error = err
return this
}
type RequestWork struct {
Id uint64
HasError bool
Args []interface{}
callable func(args ...interface{}) (interface{}, error)
}
func NewResult(request *RequestWork, result interface{}, err error) *ResultWork {
return new(ResultWork).Init(request, result, err)
}
func (this *RequestWork) Init(callable func(args ...interface{}) (interface{}, error), args ...interface{}) *RequestWork {
this.Id = uint64(time.Now().Unix()*100000) + uint64(rand.Int63n(100000))
this.callable = callable
this.Args = args
this.HasError = false
return this
}
func NewWork(callable func(args ...interface{}) (interface{}, error), args ...interface{}) *RequestWork {
return new(RequestWork).Init(callable, args...)
}
func (this *RequestWork) Call() (interface{}, error) {
if this.callable == nil {
return nil, errors.New("Callable is nil.")
}
return this.callable(this.Args...)
}
func init() {
rand.Seed(time.Now().Unix())
}
| true |
9168da3ea0307cdd4a3f54d8c8733b04a985ce5c
|
Go
|
ciarmail/twitter
|
/bd/conexionBD.go
|
UTF-8
| 888 | 2.765625 | 3 |
[] |
no_license
|
[] |
no_license
|
package bd
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
/*MongoCN almacena el objeto cliente de conexión a la base de datos*/
var MongoCN = ConectarBD()
var clientOptions = options.Client().ApplyURI("mongodb+srv://mongodb:[email protected]/myFirstDatabase?retryWrites=true&w=majority")
/*ConectarBD() para la conexión a la BD Mongo*/
func ConectarBD() *mongo.Client {
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err.Error())
return client
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err.Error())
return client
}
log.Println("Conexión Exitosa con la DB")
return client
}
/*ChequeoConnection para comprobar conexión con la DB*/
func ChequeoConnection() int {
err := MongoCN.Ping(context.TODO(), nil)
if err != nil {
return 0
}
return 1
}
| true |
f47cb4e1606f69e1b1407093f8e4ac4ca62b6687
|
Go
|
dacharat/gin-swagger
|
/cmd/handlers/health.go
|
UTF-8
| 374 | 2.671875 | 3 |
[] |
no_license
|
[] |
no_license
|
package handlers
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// HealthHandler health handler
// @summary Health Check
// @description Health checking for the service
// @id HealthHandler
// @produce json
// @response 200 {string} string "OK"
// @router /health [get]
func HealthHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"time": time.Now()})
}
| true |
b86b067874a51d22b2f0f036593512ea28fe3a0b
|
Go
|
msiebuhr/logmunch
|
/filter_test.go
|
UTF-8
| 3,933 | 3.03125 | 3 |
[
"ISC"
] |
permissive
|
[
"ISC"
] |
permissive
|
package logmunch
import (
"testing"
"time"
)
func TestPickFilter(t *testing.T) {
log := NewLogLine(
time.Now(),
"what",
map[string]string{
"keep": "this",
"discard": "that",
},
)
filter := MakePickFilter([]string{"keep"})
filteredLog := filter(&log)
if _, ok := filteredLog.Entries["discard"]; ok {
t.Errorf("Didn't expect %v to have key 'disclard'", filteredLog)
}
}
func TestRoundTimestampFilter(t *testing.T) {
n := time.Now()
log := NewLogLine(n, "what", map[string]string{})
filter := MakeRoundTimestampFilter(time.Hour)
filteredLog := filter(&log)
if n.Round(time.Hour) != filteredLog.Time {
t.Errorf("Expected %v to be %v", filteredLog.Time, n.Round(time.Hour))
}
}
func TestCompoundKey(t *testing.T) {
log := NewLogLine(time.Now(), "what", map[string]string{
"num": "123",
"str": "abc",
})
nl := MakeCompondKey("com", []string{"num", "missing", "str"})(&log)
if val, ok := nl.Entries["com"]; !ok || val != "123-∅-abc" {
t.Errorf("Expected key 'com' to be '123-∅-abc', got %v", val)
}
}
type filterTest struct {
in *LogLine
out *LogLine
}
type filterTests []filterTest
// Run all given tests though the filter
func (f filterTests) run(filter Filterer, t *testing.T) {
for _, tt := range f {
res := filter(tt.in)
// Both nil? Then OK
if tt.out == nil && res == nil {
return
}
if !tt.out.Equal(*res) {
t.Errorf("Expected log\n\t%s\nto equal\n\t%s", res, tt.out)
}
}
}
func (f filterTests) normalizeTimestamps() {
t := time.Now()
for _, tt := range f {
if tt.in != nil {
tt.in.Time = t
}
if tt.out != nil {
tt.out.Time = t
}
}
}
func TestRemoveHerokuDrainId(t *testing.T) {
tests := filterTests{
filterTest{
in: &LogLine{
Time: time.Now(),
Name: "d.f12ee345-3239-4fde-8dc6-b5d1c5656c36 what",
Entries: map[string]string{},
},
out: &LogLine{
Time: time.Now(),
Name: "what",
Entries: map[string]string{"drainId": "d.f12ee345-3239-4fde-8dc6-b5d1c5656c36"},
},
},
filterTest{
in: &LogLine{
Time: time.Now(),
Name: "no id",
Entries: map[string]string{},
},
out: &LogLine{
Time: time.Now(),
Name: "no id",
Entries: map[string]string{},
},
},
filterTest{in: nil, out: nil},
}
tests.normalizeTimestamps()
tests.run(MakeRemoveHerokuDrainId(), t)
}
func TestNormailseUrlPaths(t *testing.T) {
tests := filterTests{
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"path": "/users/NAME/avatar"}},
out: &LogLine{time.Now(), "a", map[string]string{"path": "/users/:uid/avatar", "uid": "NAME"}},
},
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"path": "/users/NAME"}},
out: &LogLine{time.Now(), "a", map[string]string{"path": "/users/:uid", "uid": "NAME"}},
},
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"path": "/no/match"}},
out: &LogLine{time.Now(), "a", map[string]string{"path": "/no/match"}},
},
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"other": "key"}},
out: &LogLine{time.Now(), "a", map[string]string{"other": "key"}},
},
filterTest{in: nil, out: nil},
}
tests.normalizeTimestamps()
tests.run(MakeNormaliseUrlPaths("path", []string{"/users/:uid/avatar", "/users/:uid"}), t)
}
func TestBucketizeKey(t *testing.T) {
tests := filterTests{
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"v": "1.1"}},
out: &LogLine{time.Now(), "a", map[string]string{"v": "1"}},
},
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"v": "411.6"}},
out: &LogLine{time.Now(), "a", map[string]string{"v": "400"}},
},
filterTest{
in: &LogLine{time.Now(), "a", map[string]string{"v": "-411.6"}},
out: &LogLine{time.Now(), "a", map[string]string{"v": "-400"}},
},
filterTest{in: nil, out: nil},
}
tests.normalizeTimestamps()
tests.run(MakeBucketizeKey("v"), t)
}
| true |
987b1346dc433dab1b8ffba8a89ab4f0176a37ec
|
Go
|
webx-top/echo
|
/engine/standard/urlValue.go
|
UTF-8
| 2,967 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package standard
import (
"net/url"
"sync"
"github.com/webx-top/echo/engine"
)
var (
_ engine.URLValuer = &UrlValue{}
_ engine.URLValuer = &Value{}
)
type UrlValue struct {
values *url.Values
initFn func() *url.Values
}
func (u *UrlValue) Add(key string, value string) {
u.init()
u.values.Add(key, value)
}
func (u *UrlValue) Del(key string) {
u.init()
u.values.Del(key)
}
func (u *UrlValue) Get(key string) string {
u.init()
return u.values.Get(key)
}
func (u *UrlValue) Gets(key string) []string {
u.init()
if v, ok := (*u.values)[key]; ok {
return v
}
return []string{}
}
func (u *UrlValue) Set(key string, value string) {
u.init()
u.values.Set(key, value)
}
func (u *UrlValue) Encode() string {
u.init()
return u.values.Encode()
}
func (u *UrlValue) All() map[string][]string {
u.init()
return *u.values
}
func (u *UrlValue) Reset(data url.Values) {
u.values = &data
}
func (u *UrlValue) init() {
if u.values != nil {
return
}
u.values = u.initFn()
}
func (u *UrlValue) Merge(data url.Values) {
u.init()
for key, values := range data {
for index, value := range values {
if index == 0 {
u.values.Set(key, value)
} else {
u.values.Add(key, value)
}
}
}
}
func NewValue(r *Request) *Value {
v := &Value{
queryArgs: &UrlValue{initFn: func() *url.Values {
q := r.url.Query()
return &q
}},
request: r,
postArgs: &UrlValue{initFn: func() *url.Values {
r.request.ParseForm()
return &r.request.PostForm
}},
}
return v
}
type Value struct {
request *Request
queryArgs *UrlValue
postArgs *UrlValue
form *url.Values
lock sync.RWMutex
}
func (v *Value) Add(key string, value string) {
v.lock.Lock()
v.init()
v.form.Add(key, value)
v.lock.Unlock()
}
func (v *Value) Del(key string) {
v.lock.Lock()
v.init()
v.form.Del(key)
v.lock.Unlock()
}
func (v *Value) Get(key string) string {
v.lock.Lock()
v.init()
val := v.form.Get(key)
v.lock.Unlock()
return val
}
func (v *Value) Gets(key string) []string {
v.lock.Lock()
defer v.lock.Unlock()
v.init()
form := *v.form
if v, ok := form[key]; ok {
return v
}
return []string{}
}
func (v *Value) Set(key string, value string) {
v.lock.Lock()
v.init()
v.form.Set(key, value)
v.lock.Unlock()
}
func (v *Value) Encode() string {
v.lock.Lock()
v.init()
val := v.form.Encode()
v.lock.Unlock()
return val
}
func (v *Value) init() {
if v.form != nil {
return
}
v.request.request.ParseForm()
v.form = &v.request.request.Form
}
func (v *Value) All() map[string][]string {
v.lock.Lock()
v.init()
m := *v.form
v.lock.Unlock()
return m
}
func (v *Value) Reset(data url.Values) {
v.lock.Lock()
v.form = &data
v.lock.Unlock()
}
func (v *Value) Merge(data url.Values) {
v.lock.Lock()
v.init()
for key, values := range data {
for index, value := range values {
if index == 0 {
v.form.Set(key, value)
} else {
v.form.Add(key, value)
}
}
}
v.lock.Unlock()
}
| true |
99cdaa992bbf3a35ea1f0be9acf51a20ac1005cf
|
Go
|
nthapaliya/wordgraph
|
/dawg/dawg_test.go
|
UTF-8
| 1,760 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package dawg_test
import (
"math/rand"
"testing"
"time"
"github.com/nthapaliya/wordgraph"
"github.com/nthapaliya/wordgraph/dawg"
)
// Notes: now its 77807. nvm
var (
random = rand.New(rand.NewSource(time.Now().Unix()))
wordlist = wordgraph.LoadFile("../files/SWOPODS.txt")
)
var badwords = []string{
"thisisa",
"aaplesnii",
"paanipary",
"meronaam",
"tveherau",
"asdfasfddafasfd",
"stdsawerjajaja",
"appleappl",
"testif",
"verificatio",
}
func wordSuite(t *testing.T, cd wordgraph.WordGraph) {
var good, bad int
for _, word := range wordlist {
if !cd.Contains(word) {
bad++
} else {
good++
}
}
if bad != 0 {
t.Errorf("bad = %d", bad)
}
good, bad = 0, 0
for _, word := range badwords {
if !cd.Contains(word) {
bad++
} else {
good++
}
}
if good != 0 {
t.Errorf("good = %d", good)
}
}
func TestVerify(t *testing.T) {
dg, err := dawg.NewFromList(wordlist)
if err != nil {
t.Error(err)
}
if err := dg.Verify(); err != nil {
t.Error(err)
}
}
func TestExists(t *testing.T) {
dg, err := dawg.NewFromList(wordlist)
if err != nil {
t.Error(err)
return
}
wordSuite(t, dg)
}
func TestList(t *testing.T) {
dg, err := dawg.NewFromList(wordlist)
if err != nil {
t.Fatal(err)
}
l := dg.List()
if expected, got := len(wordlist), len(l); expected != got {
t.Fatalf("lens don't match, expected %d, got %d", expected, got)
}
for i := range wordlist {
if expected, got := wordlist[i], l[i]; expected != got {
t.Fatalf("expected %s, got %s", expected, got)
}
}
l = dg.ListFrom("applx")
if len(l) != 0 {
t.Fatal("returning items from prefix that doesn't exist")
}
l = dg.ListFrom("apply")
if len(l) != 2 {
t.Fatal("returned list seems to be wrong, investigate here")
}
}
| true |
8dce3fab76b8b842efb586b5feb903c8b22194df
|
Go
|
almanalfaruq/alfarpos-backend
|
/routes/middleware.go
|
UTF-8
| 2,647 | 2.734375 | 3 |
[] |
no_license
|
[] |
no_license
|
package routes
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
userentity "github.com/almanalfaruq/alfarpos-backend/model/user"
"github.com/almanalfaruq/alfarpos-backend/util/response"
"github.com/golang-jwt/jwt/v4"
)
type AuthConfig struct {
SecretKey string `yaml:"secret_key"`
}
type AuthMiddleware struct {
secretKey string
}
func New(cfg AuthConfig) *AuthMiddleware {
return &AuthMiddleware{
secretKey: cfg.SecretKey,
}
}
func (m *AuthMiddleware) CheckJWTToken(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
if r.Method == http.MethodOptions {
w.WriteHeader(200)
return
}
authHeader := r.Header.Get("Authorization")
authHeaderSplit := strings.Split(authHeader, " ")
if len(authHeaderSplit) != 2 {
response.RenderJSONError(w, http.StatusUnauthorized, errors.New("Missing header Authorization"))
return
}
if strings.ToLower(authHeaderSplit[0]) != "bearer" {
response.RenderJSONError(w, http.StatusUnauthorized, errors.New("Missing header Authorization"))
return
}
token, err := jwt.ParseWithClaims(authHeaderSplit[1], &response.TokenData{}, func(token *jwt.Token) (interface{}, error) {
if method, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Signing method invalid")
} else if method != jwt.SigningMethodHS256 {
return nil, fmt.Errorf("Signing method invalid")
}
return []byte(m.secretKey), nil
})
if err != nil {
response.RenderJSONError(w, http.StatusUnauthorized, err)
return
}
claims, ok := token.Claims.(*response.TokenData)
if !ok || !token.Valid {
response.RenderJSONError(w, http.StatusUnauthorized, errors.New("Token is not valid"))
return
}
ctxUser := context.WithValue(r.Context(), userentity.CTX_USER, claims.User)
r = r.WithContext(ctxUser)
next(w, r)
}
}
func (m *AuthMiddleware) CheckCORS(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, PUT, DELETE")
if r.Method == http.MethodOptions {
w.WriteHeader(200)
return
}
next(w, r)
}
}
| true |
e643cc6d9bbb46cc8fb7f645f7be4b5a1f105a25
|
Go
|
sh-ikeda/access_zooma
|
/cmd/gen_zooma_query/main.go
|
UTF-8
| 3,382 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
func contains(a []string, s string) bool {
for _, q := range a {
if s == q {
return true
}
}
return false
}
func parseJSON(bytes []byte, d *interface{}) {
fmt.Fprintln(os.Stderr, "Parsing...")
if err := json.Unmarshal(bytes, d); err != nil {
fmt.Fprintln(os.Stderr, err)
if err, ok := err.(*json.SyntaxError); ok {
fmt.Fprintln(os.Stderr, string(bytes[err.Offset-15:err.Offset+15]))
}
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "Done. (Total %d entries)\n", len((*d).([]interface{})))
}
func main() {
a := flag.String("a", "", "comma-separated string of attributes to be collected")
b := flag.String("b", "", "comma-separated string of attributes to be collected with less priority")
s := flag.Bool("s", false, "If true, a value of attributes not listed in -a option is separated with whitespace and each word is output as a query")
l := flag.Bool("l", false, "If true, all attributes are output for entries without any attributes listed in -a")
t := flag.Int("t", 9606, "Taxonomy ID of species of interest. Default is 9606; human.")
flag.Parse()
attr := strings.Split(*a, ",")
attr_less_prior := strings.Split(*b, ",")
outputAll := *l
toBeSeparated := *s
taxIdOfInterest := *t
bytes, err := ioutil.ReadFile(flag.Arg(0))
if err != nil {
fmt.Fprintf(os.Stderr, "Usage of %s:\n %s [-a LIST] [-s] FILE\n", os.Args[0], os.Args[0])
flag.PrintDefaults()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var decode_data interface{}
parseJSON(bytes, &decode_data)
// Collect designated attributes and output them
fmt.Fprintln(os.Stderr, "Writing...")
for _, data := range decode_data.([]interface{}) {
d := data.(map[string]interface{})
sampleId := d["accession"].(string)
taxId := d["taxId"].(float64)
if int(taxId) != taxIdOfInterest {
continue
}
ch := d["characteristics"].(map[string]interface{})
has_key := false
outstr_less_prior := ""
for key, _ := range ch {
if contains(attr, key) || *a == "" {
c := ch[key].([]interface{})
x := c[0].(map[string]interface{})
value := x["text"].(string)
// in case that value has "\t"
value = strings.Replace(value, "\t", " ", -1)
fmt.Fprintf(os.Stdout, "%s\t%s\t%s\t\n", sampleId, key, value)
has_key = true
}
if contains(attr_less_prior, key) {
c := ch[key].([]interface{})
x := c[0].(map[string]interface{})
value := x["text"].(string)
// in case that value has "\t"
value = strings.Replace(value, "\t", " ", -1)
outstr_less_prior += fmt.Sprintf("%s\t%s\t%s\t\n", sampleId, key, value)
}
}
// When a sample has no specified key, output all
if !has_key && outputAll {
for key, _ := range ch {
c := ch[key].([]interface{})
x := c[0].(map[string]interface{})
value := x["text"].(string)
//slice := strings.Split(value, " ")
slice := regexp.MustCompile("[ (),./]+").Split(value, -1)
fmt.Fprintf(os.Stdout, "%s\t%s\t%s\t\n", sampleId, key, value)
if toBeSeparated && len(slice) > 1 {
for _, word := range slice {
if word != "" {
fmt.Fprintf(os.Stdout, "%s\t%s\t%s\t%s\n", sampleId, key, word, value)
}
}
}
}
}
if !has_key && outstr_less_prior != "" {
fmt.Fprintf(os.Stdout, "%s", outstr_less_prior)
}
}
fmt.Fprintln(os.Stderr, "Done.")
}
| true |
1640ccc371b0781da7abc077f9db310c673e85fd
|
Go
|
cipherboy/hddb
|
/check.go
|
UTF-8
| 1,951 | 2.765625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"log"
)
func CheckAllFiles() {
tx, err := DB.Begin()
if err != nil {
log.Fatal("Unable to begin transaction: ", err)
}
var files []FileList = getAllFileNamesDB(tx)
fmt.Println("Checking:", len(files), "files")
var onepercent int = len(files) / 100
for i, file := range files {
if i != 0 && (i%onepercent) == 0 {
fmt.Println(".")
}
if !file.Ignored {
var hashes []FileHashes = getAllHashesDB(tx, file.FileName)
var issue = false
for i, nhash := range hashes {
if i+1 < len(hashes) {
var ohash FileHashes = hashes[i+1]
if nhash.Size != ohash.Size {
fmt.Println(nhash.FileName, ":::: changed sizes between", ohash.ScanDate, "and", nhash.ScanDate)
issue = true
break
} else if nhash.MD5 != "" && ohash.MD5 != "" && nhash.MD5 != ohash.MD5 {
fmt.Println(nhash.FileName, ":::: md5 changed between", ohash.ScanDate, "and", nhash.ScanDate)
issue = true
break
} else if nhash.SHA1 != "" && ohash.SHA1 != "" && nhash.SHA1 != ohash.SHA1 {
fmt.Println(nhash.FileName, ":::: sha1 changed between", ohash.ScanDate, "and", nhash.ScanDate)
issue = true
break
} else if nhash.SHA256 != "" && ohash.SHA256 != "" && nhash.SHA256 != ohash.SHA256 {
fmt.Println(nhash.FileName, ":::: sha256 changed between", ohash.ScanDate, "and", nhash.ScanDate)
issue = true
break
} else if nhash.Tiger != "" && ohash.Tiger != "" && nhash.Tiger != ohash.Tiger {
fmt.Println(nhash.FileName, ":::: tiger changed between", ohash.ScanDate, "and", nhash.ScanDate)
issue = true
break
} else if nhash.Whirlpool != "" && ohash.Whirlpool != "" && nhash.Whirlpool != ohash.Whirlpool {
fmt.Println(nhash.FileName, ":::: whirlpool changed between", ohash.ScanDate, "and", nhash.ScanDate)
issue = true
break
}
}
}
if !issue {
issue = true
}
}
}
tx.Commit()
}
| true |
cd8f5db876f3c506a8715c1613794ef38221d201
|
Go
|
vkondula/advent-of-code-2018-go
|
/3.1.go
|
UTF-8
| 893 | 3.125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"./lib"
"regexp"
"strconv"
"fmt"
)
type Field struct{
taken bool
overlapping bool
}
func (field *Field) aquire() {
if field.taken{
field.overlapping = true
}
field.taken = true
}
func main() {
lines := lib.GetItems("inputs/3.txt")
const size = 1000
var matrix [size][size]Field
re, _ := regexp.Compile(`#\d+ @ (\d+),(\d+): (\d+)x(\d+)`)
for _, line := range lines{
matched := re.FindStringSubmatch(line)
x, _ := strconv.Atoi(matched[1])
y, _ := strconv.Atoi(matched[2])
x_delta, _ := strconv.Atoi(matched[3])
y_delta, _ := strconv.Atoi(matched[4])
for x_i := x; x_i < (x + x_delta); x_i++ {
for y_i := y; y_i < (y + y_delta); y_i++ {
matrix[x_i][y_i].aquire()
}
}
}
counter := 0
for _, line := range matrix {
for _, row := range line {
if row.overlapping {
counter++
}
}
}
fmt.Printf("%d\n", counter)
}
| true |
85b0d5778416e39dfe27f84aec97a73f82f5a42b
|
Go
|
cosiner/go-schema
|
/decoder.go
|
UTF-8
| 2,248 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package schema
import (
"fmt"
"reflect"
)
type DecoderSource interface {
Get(source, field string) []string
}
type Decoder struct {
parser *Parser
}
func NewDecoder(p *Parser) (*Decoder, error) {
return &Decoder{parser: p}, nil
}
func (d *Decoder) decodeStringsToType(f *fieldInfo, v []string) (reflect.Value, bool, error) {
l := len(v)
if f.IsSlice {
refv := reflect.MakeSlice(f.Field.Type, 0, l)
for _, v := range v {
val, err := f.Encoding.Decode(v)
if err != nil {
return reflect.Value{}, false, err
}
refv = reflect.Append(refv, reflect.ValueOf(val))
}
return refv, true, nil
}
if l != 1 {
return reflect.Value{}, false, fmt.Errorf("multiple values of non-slice field is not allowed: %v", v)
}
if v[0] == "" {
return reflect.Value{}, false, nil
}
val, err := f.Encoding.Decode(v[0])
if err != nil {
return reflect.Value{}, false, err
}
return reflect.ValueOf(val), true, nil
}
func (d *Decoder) decodeField(refv reflect.Value, field *fieldInfo, v []string) (bool, error) {
val, ok, err := d.decodeStringsToType(field, v)
if err != nil || !ok {
return false, err
}
if val.Type() != field.Field.Type {
return false, fmt.Errorf("different decoded value type: expect %s, but got %s", field.Field.Type, val.Type())
}
fieldv := refv.FieldByIndex(field.Field.Index)
fieldv.Set(val)
return true, nil
}
func (d *Decoder) Decode(s DecoderSource, v interface{}) error {
refv := reflect.ValueOf(v)
if refv.Type().Kind() != reflect.Ptr {
return fmt.Errorf("decode destination type isn't pointer: %s", refv.Type().String())
}
refv = refv.Elem()
typInfo, err := d.parser.Parse(refv.Type())
if err != nil {
return err
}
for i := range typInfo.fields {
field := &typInfo.fields[i]
var updatedFrom fieldSource
for _, source := range field.Sources {
v := s.Get(source.Source, source.Name)
if len(v) == 0 {
continue
}
if updatedFrom.Source != "" {
return fmt.Errorf("duplicated field values from different sources: %s, %s", updatedFrom, source)
}
ok, err := d.decodeField(refv, field, v)
if err != nil {
return fmt.Errorf("invalid field values: %s, %s", source, err.Error())
}
if ok {
updatedFrom = source
}
}
}
return nil
}
| true |
0a28fc7028d6dc85f89f513a705842ab9ba63ec7
|
Go
|
vinbyte/aws-go-localstack-example
|
/aws-sdk-go-v2/sns/publish-message/main.go
|
UTF-8
| 2,194 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"context"
"flag"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sns"
)
type SNSLocalstack struct {
message string
topicARN string
localstackURL string
region string
}
// setup the data by collecting from args parameter
func (s *SNSLocalstack) setup() {
msg := flag.String("m", "", "The message to send to the subscribed users of the topic")
topicARN := flag.String("t", "", "The ARN of the topic to which the user subscribes")
localstackURL := flag.String("u", "http://localhost:4566", "The Localstack url. Default : http://localhost:4566")
region := flag.String("r", "us-east-1", "The region of localstack. Default: us-east-1")
flag.Parse()
if *msg == "" || *topicARN == "" {
fmt.Println("You must supply a message and topic ARN")
fmt.Println("-m MESSAGE -t TOPIC-ARN")
return
}
s.topicARN = *topicARN
s.message = *msg
s.localstackURL = *localstackURL
s.region = *region
}
func (s *SNSLocalstack) publishMessage() {
ctx := context.TODO()
// customResolver used to handle the localstack url we given to aws-sdk-go-v2
customResolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {
if s.localstackURL != "" {
return aws.Endpoint{
PartitionID: "aws",
URL: s.localstackURL,
SigningRegion: s.region,
}, nil
}
// returning EndpointNotFoundError will allow the service to fallback to it's default resolution
return aws.Endpoint{}, &aws.EndpointNotFoundError{}
})
cfg, err := config.LoadDefaultConfig(
ctx,
config.WithRegion(s.region),
config.WithEndpointResolver(customResolver),
)
if err != nil {
panic("configuration error, " + err.Error())
}
client := sns.NewFromConfig(cfg)
input := &sns.PublishInput{
Message: &s.message,
TopicArn: &s.topicARN,
}
result, err := client.Publish(ctx, input)
if err != nil {
fmt.Println("Got an error publishing the message:")
fmt.Println(err)
return
}
fmt.Println("Message ID: " + *result.MessageId)
}
func main() {
snsLocalstack := SNSLocalstack{}
snsLocalstack.setup()
snsLocalstack.publishMessage()
}
| true |
954d4f83d6e3c2b5471601aa0432395ea1a0e8dd
|
Go
|
miniboxai/minibox
|
/pkg/apiserver/oauth_storage/storage.go
|
UTF-8
| 2,757 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
package oauth_storage
import (
"fmt"
osin "github.com/RangelReale/osin"
"minibox.ai/minibox/pkg/models"
)
type Storage struct {
clients *ClientStore
authorize *AuthorizeStore
access *TokenStore
refresh *RefreshStore
initializes []StorageHandler
}
type StorageHandler func(*Storage)
func NewStorage(db *models.Database) *Storage {
r := &Storage{
initializes: make([]StorageHandler, 0),
}
r.clients = NewClientStore(db)
r.authorize = NewAuthorizeStore(db)
r.access = NewTokenStore(db)
r.refresh = NewRefreshStore(db)
// r.access.SetRefreshStore(r.refresh)
// r.refresh.SetTokenStore(r.access)
r.clients.Set("1234", Client(models.OAuth2Client{
ID: "1234",
Secret: "aabbccdd",
RedirectUri: "http://localhost:14000/oauth/appauth",
}))
r.clients.Set("12345", Client(models.OAuth2Client{
ID: "12345",
Secret: "asdfasdf",
RedirectUri: "http://localhost:14001/auth",
}))
r.init()
return r
}
func (s *Storage) init() {
EachInitializer(s)
}
func (s *Storage) Clone() osin.Storage {
return s
}
func (s *Storage) Close() {
}
func (s *Storage) GetClient(id string) (osin.Client, error) {
fmt.Printf("GetClient: %s\n", id)
return s.clients.Get(id)
}
func (s *Storage) SetClient(id string, client osin.Client) error {
fmt.Printf("SetClient: %s\n", id)
return s.clients.Set(id, client)
}
func (s *Storage) SaveAuthorize(data *osin.AuthorizeData) error {
fmt.Printf("SaveAuthorize: %s\n", data.Code)
return s.authorize.Set(data.Code, data)
}
func (s *Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
fmt.Printf("LoadAuthorize: %s\n", code)
return s.authorize.Get(code)
}
func (s *Storage) RemoveAuthorize(code string) error {
fmt.Printf("RemoveAuthorize: %s\n", code)
return s.authorize.Remove(code)
}
func (s *Storage) SaveAccess(data *osin.AccessData) error {
fmt.Printf("SaveAccess: %s\n", data.AccessToken)
if err := s.access.Set(data.AccessToken, data); err != nil {
return err
}
if data.RefreshToken != "" {
s.refresh.Set(data.RefreshToken, data)
}
return nil
}
func (s *Storage) LoadAccess(code string) (*osin.AccessData, error) {
fmt.Printf("LoadAccess: %s\n", code)
return s.access.Get(code)
}
func (s *Storage) RemoveAccess(code string) error {
fmt.Printf("RemoveAccess: %s\n", code)
return s.access.Remove(code)
}
func (s *Storage) LoadRefresh(code string) (*osin.AccessData, error) {
fmt.Printf("LoadRefresh: %s\n", code)
var (
token *osin.AccessData
err error
)
if token, err = s.refresh.Get(code); err != nil {
return nil, err
}
return s.access.Get(token.AccessToken)
}
func (s *Storage) RemoveRefresh(code string) error {
fmt.Printf("RemoveRefresh: %s\n", code)
return s.refresh.Remove(code)
}
| true |
728fe2b649f47a2f02ee2141914c0416e8d7a56a
|
Go
|
erning/rsca
|
/pkg/rsca/rsca.go
|
UTF-8
| 2,508 | 2.625 | 3 |
[] |
no_license
|
[] |
no_license
|
package rsca
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"math/big"
"time"
"github.com/pkg/errors"
)
func IssueClientCertificate(cacert *x509.Certificate, cakey *rsa.PrivateKey, pub *rsa.PublicKey) (*x509.Certificate, error) {
now := time.Now()
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, errors.WithStack(err)
}
commonName, err := fingerprint(pub)
if err != nil {
return nil, errors.WithStack(err)
}
template := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
// SerialNumber: uuid.New().String(),
CommonName: commonName,
},
NotBefore: now,
NotAfter: now.Add(time.Hour * 24 * 3650),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, template, cacert, pub, cakey)
if err != nil {
return nil, errors.WithStack(err)
}
cert, err := x509.ParseCertificate(certDER)
return cert, errors.WithStack(err)
}
func fingerprint(pub *rsa.PublicKey) (string, error) {
data, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
return "", errors.WithStack(err)
}
fp := sha256.Sum256(data)
return hex.EncodeToString(fp[:]), nil
}
// Parse from PEM
func ParsePrivateKey(data []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(data)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
return priv, errors.WithStack(err)
}
// Parse from PEM
func ParsePublicKey(data []byte) (*rsa.PublicKey, error) {
block, _ := pem.Decode(data)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, errors.WithStack(err)
}
rsapub, ok := pub.(*rsa.PublicKey)
if !ok {
return nil, errors.New("not RSA public key")
}
return rsapub, nil
}
// Parse from PEM
func ParseCertificate(data []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(data)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
cert, err := x509.ParseCertificate(block.Bytes)
return cert, errors.WithStack(err)
}
| true |
5e3c47aea897fef79aca9b8c9514c975af92ab1a
|
Go
|
ningchanka/ning-go-hello
|
/handler.go
|
UTF-8
| 455 | 3.15625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// MyHandler is the interface
type MyHandler interface {
HelloWorld(c *gin.Context)
}
type myHandler struct {
}
// NewMyHandler is a function new instance
func NewMyHandler() MyHandler {
return &myHandler{}
}
func (h *myHandler) HelloWorld(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"message": fmt.Sprintf("Hello World! %s", time.Now()),
})
}
| true |
64ce4ed4b12097de3d5c3013565caadd57afa3ae
|
Go
|
stillwondering/minar
|
/cmd/minar/main.go
|
UTF-8
| 1,551 | 2.78125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/stillwondering/minar/cmd/minar/templates"
)
const (
AppName = "minar"
Version = "0.1.0"
ListenAddress = ":8080"
)
func main() {
if err := run(os.Args[1:], os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(args []string, out io.Writer) error {
log.SetOutput(out)
cfg, err := configFromCmdline(args)
if err != nil {
return err
}
if cfg.printVersion {
fmt.Fprintln(out, Version)
return nil
}
fs := http.FileServer(http.Dir("assets"))
mux := http.NewServeMux()
mux.Handle("/assets/", http.StripPrefix("/assets/", fs))
mux.HandleFunc("/", index())
return http.ListenAndServe(cfg.listenAddress, mux)
}
type config struct {
printVersion bool
listenAddress string
}
func configFromCmdline(cmdline []string) (*config, error) {
fs := flag.NewFlagSet(AppName, flag.ExitOnError)
printVersion := fs.Bool("version", false, "print version information")
listenAddress := fs.String("address", ListenAddress, "listen on this address")
if err := fs.Parse(cmdline); err != nil {
return nil, err
}
return &config{
printVersion: *printVersion,
listenAddress: *listenAddress,
}, nil
}
func index() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
buf := bytes.Buffer{}
if err := templates.Index(&buf); err != nil {
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
io.Copy(rw, &buf)
}
}
| true |
b7ec1f12b747b582a63608c3c3c3a13d339ca2f4
|
Go
|
unixpickle/gocube
|
/cubie_corners.go
|
UTF-8
| 5,821 | 3.625 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
package gocube
import "strconv"
// A CubieCorner represents a physical corner of a cube.
//
// To understand the meaning of a CubieCorner's fields, you must first
// understand the coordinate system. There are there axes, x, y, and z.
// The x axis is 0 at the L face and 1 at the R face.
// The y axis is 0 at the D face and 1 at the U face.
// The z axis is 0 at the B face and 1 at the F face.
//
// A corner piece's index is determined by it's original position on the cube.
// The index is a binary number of the form ZYX, where Z is the most significant
// digit. Thus, the BLD corner is 0, the BRU corner is 3, the FRU corner is 7,
// etc.
//
// The orientation of a corner tells how it is twisted. It is an axis number 0,
// 1, or 2 for x, y, or z respectively. It indicates the direction normal to the
// white or yellow sticker (i.e. the sticker that is usually normal to the y
// axis). The corners of a solved cube all have an orientation of 1.
type CubieCorner struct {
Piece int
Orientation int
}
// CubieCorners represents the corners of a cube.
type CubieCorners [8]CubieCorner
// SolvedCubieCorners generates the corners of a solved cube.
func SolvedCubieCorners() CubieCorners {
var res CubieCorners
for i := 0; i < 8; i++ {
res[i].Piece = i
res[i].Orientation = 1
}
return res
}
// HalfTurn performs a 180 degree turn on a given face.
func (c *CubieCorners) HalfTurn(face int) {
// A double turn is really just two swaps.
switch face {
case 1: // Top face
c[2], c[7] = c[7], c[2]
c[3], c[6] = c[6], c[3]
case 2: // Bottom face
c[0], c[5] = c[5], c[0]
c[1], c[4] = c[4], c[1]
case 3: // Front face
c[5], c[6] = c[6], c[5]
c[4], c[7] = c[7], c[4]
case 4: // Back face
c[0], c[3] = c[3], c[0]
c[1], c[2] = c[2], c[1]
case 5: // Right face
c[1], c[7] = c[7], c[1]
c[3], c[5] = c[5], c[3]
case 6: // Left face
c[0], c[6] = c[6], c[0]
c[2], c[4] = c[4], c[2]
default:
panic("Unsupported half-turn applied to CubieCorners: " +
strconv.Itoa(face))
}
}
// Move applies a face turn to the corners.
func (c *CubieCorners) Move(m Move) {
if m >= 12 {
c.HalfTurn(m.Face())
} else {
c.QuarterTurn(m.Face(), m.Turns())
}
}
// QuarterTurn performs a 90 degree turn on a given face.
func (c *CubieCorners) QuarterTurn(face, turns int) {
// This code is not particularly graceful, but it is rather efficient and
// quite readable compared to a pure array of transformations.
switch face {
case 1: // Top face
if turns == 1 {
c[2], c[3], c[7], c[6] = c[6], c[2], c[3], c[7]
} else {
c[6], c[2], c[3], c[7] = c[2], c[3], c[7], c[6]
}
// Swap orientation 0 with orientation 2.
for _, i := range []int{2, 3, 6, 7} {
c[i].Orientation = 2 - c[i].Orientation
}
case 2: // Bottom face
if turns == 1 {
c[4], c[0], c[1], c[5] = c[0], c[1], c[5], c[4]
} else {
c[0], c[1], c[5], c[4] = c[4], c[0], c[1], c[5]
}
// Swap orientation 0 with orientation 2.
for _, i := range []int{0, 1, 4, 5} {
c[i].Orientation = 2 - c[i].Orientation
}
case 3: // Front face
if turns == 1 {
c[6], c[7], c[5], c[4] = c[4], c[6], c[7], c[5]
} else {
c[4], c[6], c[7], c[5] = c[6], c[7], c[5], c[4]
}
// Swap orientation 0 with orientation 1.
for _, i := range []int{4, 5, 6, 7} {
if c[i].Orientation == 0 {
c[i].Orientation = 1
} else if c[i].Orientation == 1 {
c[i].Orientation = 0
}
}
case 4: // Back face
if turns == 1 {
c[0], c[2], c[3], c[1] = c[2], c[3], c[1], c[0]
} else {
c[2], c[3], c[1], c[0] = c[0], c[2], c[3], c[1]
}
// Swap orientation 0 with orientation 1.
for _, i := range []int{0, 1, 2, 3} {
if c[i].Orientation == 0 {
c[i].Orientation = 1
} else if c[i].Orientation == 1 {
c[i].Orientation = 0
}
}
case 5: // Right face
if turns == 1 {
c[7], c[3], c[1], c[5] = c[5], c[7], c[3], c[1]
} else {
c[5], c[7], c[3], c[1] = c[7], c[3], c[1], c[5]
}
// Swap orientation 2 with orientation 1.
for _, i := range []int{1, 3, 5, 7} {
if c[i].Orientation == 1 {
c[i].Orientation = 2
} else if c[i].Orientation == 2 {
c[i].Orientation = 1
}
}
case 6: // Left face
if turns == 1 {
c[4], c[6], c[2], c[0] = c[6], c[2], c[0], c[4]
} else {
c[6], c[2], c[0], c[4] = c[4], c[6], c[2], c[0]
}
// Swap orientation 2 with orientation 1.
for _, i := range []int{0, 2, 4, 6} {
if c[i].Orientation == 1 {
c[i].Orientation = 2
} else if c[i].Orientation == 2 {
c[i].Orientation = 1
}
}
default:
panic("Unsupported quarter-turn applied to CubieCorners: " +
strconv.Itoa(face))
}
}
// Solved returns true if all the corners are properly positioned and oriented.
func (c *CubieCorners) Solved() bool {
for i := 0; i < 8; i++ {
if c[i].Piece != i || c[i].Orientation != 1 {
return false
}
}
return true
}
// fixLastOrientation orients the final corner (corner 7),
// assuming all of the other corners are correct.
func (c *CubieCorners) fixLastOrientation() {
// Start by orienting the final corner upright. Then, solve a series of
// adjacent corners in order, twisting the next corner in the opposite
// direction to preserve orientation. The resulting orientation of the
// final corner tells us the inverse of what the orientation should have
// been.
c[7].Orientation = 1
var orientations [8]int
for i, x := range []int{0, 1, 5, 4, 6, 2, 3, 7} {
orientations[i] = c[x].Orientation
}
for i := 0; i < 7; i++ {
thisOrientation := orientations[i]
nextOrientation := orientations[i+1]
if thisOrientation == 2 {
orientations[i+1] = (nextOrientation + 2) % 3
} else if thisOrientation == 0 {
orientations[i+1] = (nextOrientation + 1) % 3
}
}
if orientations[7] == 0 {
c[7].Orientation = 2
} else if orientations[7] == 2 {
c[7].Orientation = 0
}
}
| true |
6234153d9cae5efb50e03ea641e81781814d8d5e
|
Go
|
rahulp391/go-REST-API
|
/employee.go
|
UTF-8
| 1,702 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package controller
import (
"go-rest/model"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
//GetUsers ... Get all users
func GetEmployees(c *gin.Context) {
var employee []model.Employee
err := model.GetAllEmployees(&employee)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
} else {
c.JSON(http.StatusOK, employee)
}
}
//CreateUser ... Create User
func CreateEmployee(c *gin.Context) {
var employee model.Employee
c.BindJSON(&employee)
err := model.CreateEmployee(&employee)
if err != nil {
fmt.Println(err.Error())
c.AbortWithStatus(http.StatusNotFound)
} else {
c.JSON(http.StatusOK, employee)
}
}
//GetUserByID ... Get the user by id
func GetEmployeeByID(c *gin.Context) {
id := c.Params.ByName("id")
var employee model.Employee
err := model.GetEmployeeByID(&employee, id)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
} else {
c.JSON(http.StatusOK, employee)
}
}
//UpdateUser ... Update the user information
func UpdateEmployee(c *gin.Context) {
var employee model.Employee
id := c.Params.ByName("id")
err := model.GetEmployeeByID(&employee, id)
if err != nil {
c.JSON(http.StatusNotFound, employee)
}
c.BindJSON(&employee)
err = model.UpdateEmployee(&employee, id)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
} else {
c.JSON(http.StatusOK, employee)
}
}
//DeleteUser ... Delete the user
func DeleteEmployee(c *gin.Context) {
var employee model.Employee
id := c.Params.ByName("id")
err := model.DeleteEmployee(&employee, id)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
} else {
c.JSON(http.StatusOK, gin.H{"id" + id: "is deleted"})
}
}
| true |
7cbd3c680d3fb2a14638ded4d19b6cdcd3f0a974
|
Go
|
service-exposer/exposer
|
/listener/utils/websocket.go
|
UTF-8
| 1,733 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package utils
import (
"net"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/juju/errors"
"github.com/service-exposer/exposer/listener"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
HandshakeTimeout: 15 * time.Second,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var dialer = websocket.Dialer{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
HandshakeTimeout: 15 * time.Second,
}
func WebsocketHandlerListener(addr net.Addr) (net.Listener, http.Handler, error) {
var (
mutex = new(sync.Mutex)
closed = false
)
accepts := make(chan *websocket.Conn)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
mutex.Lock()
defer mutex.Unlock()
if closed {
return
}
accepts <- ws
})
closeFn := func() error {
mutex.Lock()
defer mutex.Unlock()
if !closed {
close(accepts)
closed = true
}
return nil
}
return listener.Websocket(accepts, closeFn, addr), handler, nil
}
func WebsocketListener(network, addr string) (net.Listener, error) {
ln, err := net.Listen(network, addr)
if err != nil {
return nil, errors.Trace(err)
}
wsln, handler, err := WebsocketHandlerListener(ln.Addr())
if err != nil {
return nil, errors.Trace(err)
}
server := http.Server{
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
Handler: handler,
}
go func() {
server.Serve(ln)
}()
return wsln, nil
}
func DialWebsocket(url string) (net.Conn, error) {
ws, _, err := dialer.Dial(url, nil)
if err != nil {
return nil, errors.Trace(err)
}
return listener.NewWebsocketConn(ws), nil
}
| true |
e7c54cce5c9e2756a55462f7acfe6168c3fd4890
|
Go
|
E1101/LearningGolang
|
/14_slice/10_Passing slices between functions/main.go
|
UTF-8
| 501 | 3.96875 | 4 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package main
// Since the data associated with a slice is contained in
// the underlying array, there are no problems passing a
// copy of a slice to any function. Only the slice is being
// copied, not the underlying array
func main() {
// Allocate a slice of 1 million integers.
slice := make([]int, 1e6)
// Pass the slice to the function foo.
slice = foo(slice)
}
// Function foo accepts a slice of integers and returns the slice back.
func foo(slice []int) []int {
// ..
return slice
}
| true |
7636063b1d61df79ba6821f837e5efd8d1d69985
|
Go
|
tnir/gitaly
|
/internal/git/protocol_test.go
|
UTF-8
| 737 | 2.671875 | 3 |
[
"BSD-3-Clause",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"GPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-google-patent-license-golang",
"MPL-2.0"
] |
permissive
|
[
"BSD-3-Clause",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"GPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-google-patent-license-golang",
"MPL-2.0"
] |
permissive
|
package git
import (
"testing"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v14/internal/testhelper"
)
type fakeProtocolMessage struct {
protocol string
}
func (f fakeProtocolMessage) GetGitProtocol() string {
return f.protocol
}
func TestGitProtocolEnv(t *testing.T) {
for _, tt := range []struct {
desc string
msg fakeProtocolMessage
env []string
}{
{
desc: "no V2 request",
env: nil,
},
{
desc: "V2 request",
msg: fakeProtocolMessage{protocol: "version=2"},
env: []string{"GIT_PROTOCOL=version=2"},
},
} {
t.Run(tt.desc, func(t *testing.T) {
ctx := testhelper.Context(t)
actual := gitProtocolEnv(ctx, tt.msg)
require.Equal(t, tt.env, actual)
})
}
}
| true |
27b4bb674a34e7c1d85db21dfb6f68d6e6bdd9ba
|
Go
|
tobischo/goinvaders
|
/shot.go
|
UTF-8
| 1,306 | 3 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"time"
"github.com/nsf/termbox-go"
)
//Shot fired by a ship
type Shot struct {
positionX int
positionY int
direction int
stopCh chan bool
ship *Ship
fg termbox.Attribute
bg termbox.Attribute
}
func (shot *Shot) run() {
shot.draw()
for {
select {
case <-time.After(250000 * time.Microsecond):
shot.clear()
shot.positionY += shot.direction
shot.draw()
shot.detectCollision()
case <-shot.stopCh:
shot.clear()
return
}
}
}
func (shot *Shot) draw() {
if shot.positionY < 0 || shot.positionY > shot.ship.size.height {
shot.stopCh <- true
}
termbox.SetCell(
shot.positionX,
shot.positionY,
'|',
shot.fg,
shot.bg,
)
}
func (shot *Shot) detectCollision() {
// Avoid checking if the shot has reached the top corner
if shot.positionY >= 0 {
ship := shot.ship.matrix[shot.positionX][shot.positionY]
// Check if there is a ship (which did not fire the shot)
if ship != nil && ship != shot.ship {
// Check for player controlled ship
if ship.control {
cleanExit()
} else {
ship.stopCh <- true
shot.clear()
shot.stopCh <- true
}
}
}
}
func (shot *Shot) clear() {
termbox.SetCell(
shot.positionX,
shot.positionY,
' ',
termbox.ColorDefault,
termbox.ColorDefault,
)
}
| true |
7a5001f450a491400ee2180a3d247bbe7a452442
|
Go
|
jasondelponte/resizeImages
|
/saveGIF.go
|
UTF-8
| 1,299 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"github.com/nfnt/resize"
"image"
"image/color"
"image/gif"
"io"
)
type GIFManipulator struct {
gif *gif.GIF
}
func NewGIFManipulator(reader io.ReadSeeker, format string, image image.Image) (Manipulator, error) {
if _, err := reader.Seek(0, 0); err != nil {
return nil, err
}
g, err := gif.DecodeAll(reader)
if err != nil {
return nil, err
}
return &GIFManipulator{gif: g}, nil
}
func (m *GIFManipulator) Format() string {
return "gif"
}
func (m *GIFManipulator) Bounds() image.Rectangle {
if len(m.gif.Image) == 0 {
return image.Rectangle{}
}
return m.gif.Image[0].Bounds()
}
func (m *GIFManipulator) Resize(width, height uint) {
for i, v := range m.gif.Image {
resizedImg := resize.Resize(width, height, v, resize.NearestNeighbor)
m.gif.Image[i] = imageToPalleted(resizedImg, m.gif.Image[i].Palette)
}
}
func (m *GIFManipulator) Save(writer io.Writer) error {
return gif.EncodeAll(writer, m.gif)
}
func imageToPalleted(img image.Image, palette color.Palette) *image.Paletted {
palleted := image.NewPaletted(img.Bounds(), palette)
for x := palleted.Bounds().Min.X; x < palleted.Bounds().Max.X; x++ {
for y := palleted.Bounds().Min.Y; y < palleted.Bounds().Max.Y; y++ {
palleted.Set(x, y, img.At(x, y))
}
}
return palleted
}
| true |
2e41e7f8be6384d71b896025444f60af5229434b
|
Go
|
reaprman/GolangTraining
|
/17_data-structures/02_slice/12_multi-dmensional/04_comparing-shorthand_var_make/01_shorthand-slice/main.go
|
UTF-8
| 568 | 3.015625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
student := []string{}
students := [][]string{}
student[0] = "Todd"
//student = append(student, "Todd")
fmt.Println(student)
fmt.Println(students)
}
/*
Underlying array has not been specified
1st Run Result:
panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
C:/Users/ryang/Documents/Projects/goprojects/src/github.com/reaprman/GolangTra
ining/17_data-structures/02_slice/12_multi-dmensional/04_comparing-shorthand_var_make/
main.go:8 +0x49
exit status 2
2nd Run Result:
[Todd]
[]
*/
| true |
b0fb4e22f230a2ba108364e24ca4356cbac9216e
|
Go
|
loofahs/DevOps
|
/src/heidsoft.go
|
UTF-8
| 616 | 3.34375 | 3 |
[] |
no_license
|
[] |
no_license
|
// heidsoft
package main
import (
"fmt"
)
func main() {
var i=42
var s = "Answer"
fmt.Print(s,"is",i,3.14,'\n',"\n")
//声明变量
//方法一
var a int
var b bool
a = 15
b = false
//方法二
c := 20
d := false
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
type NameAge struct{
name string
age int
}
pp := new(NameAge)
pp.age = 25
pp.name = "heidsoft"
fmt.Printf("%v\n",pp);
testIf();
}
//判断语句if
func testIf(){
var aa int
aa = 15
if aa > 0 {
aa = -aa
}
fmt.Println("-----test if-----")
fmt.Println(aa)
fmt.Println("-----test end----")
}
| true |
c0d73baf15d8c997e21e4f7a66c8587104889617
|
Go
|
alissonbrunosa/shortner
|
/internal/stores/redis_url_store.go
|
UTF-8
| 550 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package stores
import "github.com/go-redis/redis"
type RedisURLStore struct {
Provider *redis.Client
}
func NewRedisURLStore() *RedisURLStore {
return &RedisURLStore{
Provider: redis.NewClient(&redis.Options{
DB: 0,
Addr: "redis:6379",
Password: "",
}),
}
}
func (this RedisURLStore) Create(key string, url string) error {
err := this.Provider.Set(key, url, 0).Err()
if err != nil {
return err
}
return nil
}
func (this RedisURLStore) Find(key string) (string, error) {
return this.Provider.Get(key).Result()
}
| true |
f6d0e6814dc0be9baa8e912181861ac075aedbbc
|
Go
|
VinozzZ/Go-Practice
|
/Gophercises/quiz/main.go
|
UTF-8
| 1,068 | 3.625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"encoding/csv"
"fmt"
"log"
"math/rand"
"os"
"strings"
)
/*
Struct for csv line
*/
type CsvLine struct {
Question string
Answer string
}
func checkErr(err error) {
if err != nil {
log.Fatalln(err)
}
}
func main() {
filename := "problems.csv"
problems := readCsvFile(filename)
randomNum := rand.Intn(len(problems))
currentProblem := problems[randomNum]
reader := bufio.NewReader(os.Stdin)
fmt.Println(currentProblem.Question)
answer, err := reader.ReadString('\n')
checkErr(err)
currentAnswer := strings.Replace(answer, "\n", "", -1)
if currentAnswer == currentProblem.Answer {
fmt.Println("Hooray, you got it right!")
} else {
fmt.Println("Your answer is ", answer, "Good luck next time")
}
}
func readCsvFile(fileName string) []CsvLine {
var data []CsvLine
f, err := os.Open(fileName)
defer f.Close()
r := csv.NewReader(f)
lines, err := r.ReadAll()
checkErr(err)
for _, line := range lines {
data = append(data, CsvLine{
Question: line[0],
Answer: line[1],
})
}
return data
}
| true |
77f762bdc2861ffe3ac83cf734600e1583fd7230
|
Go
|
HeliosMC89/atreugo
|
/middlewares/cors_test.go
|
UTF-8
| 4,262 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package middlewares
import (
"testing"
"github.com/savsgio/atreugo/v11"
"github.com/valyala/fasthttp"
)
func Test_NewCorsMiddleware(t *testing.T) { //nolint:funlen
type args struct {
method string
origin string
vary string
cors CORS
}
type want struct {
origin string
vary string
allowedHeaders string
allowedMethods string
exposedHeaders string
allowCredentials string
allowMaxAge string
}
tests := []struct {
args args
want want
}{
{
args: args{
method: "OPTIONS",
vary: "Accept-Encoding",
origin: "https://cors.test",
cors: CORS{
AllowedOrigins: []string{"https://other.domain.test", "https://cors.test"},
AllowedHeaders: []string{"Content-Type", "X-Custom"},
AllowedMethods: []string{"GET", "POST", "DELETE"},
ExposedHeaders: []string{"Content-Length", "Authorization"},
AllowCredentials: true,
AllowMaxAge: 5600,
},
},
want: want{
origin: "https://cors.test",
vary: "Accept-Encoding, Origin",
allowedHeaders: "Content-Type, X-Custom",
allowedMethods: "GET, POST, DELETE",
exposedHeaders: "Content-Length, Authorization",
allowCredentials: "true",
allowMaxAge: "5600",
},
},
{
args: args{
method: "POST",
vary: "",
origin: "https://cors.test",
cors: CORS{
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"Content-Type", "X-Custom"},
AllowedMethods: []string{"GET", "POST", "DELETE"},
ExposedHeaders: []string{"Content-Length", "Authorization"},
AllowCredentials: true,
AllowMaxAge: 5600,
},
},
want: want{
origin: "https://cors.test",
vary: "Origin",
allowedHeaders: "",
allowedMethods: "",
exposedHeaders: "Content-Length, Authorization",
allowCredentials: "true",
allowMaxAge: "",
},
},
{
args: args{
method: "POST",
vary: "",
origin: "https://cors.test",
cors: CORS{
AllowedOrigins: []string{"https://other.domain.test"},
AllowedHeaders: []string{"Content-Type", "X-Custom"},
AllowedMethods: []string{"GET", "POST", "DELETE"},
ExposedHeaders: []string{"Content-Length", "Authorization"},
AllowCredentials: true,
AllowMaxAge: 5600,
},
},
want: want{
origin: "",
vary: "",
allowedHeaders: "",
allowedMethods: "",
exposedHeaders: "",
allowCredentials: "",
allowMaxAge: "",
},
},
}
for _, test := range tests {
tt := test
t.Run("", func(t *testing.T) {
m := NewCORSMiddleware(tt.args.cors)
ctx := new(atreugo.RequestCtx)
ctx.RequestCtx = new(fasthttp.RequestCtx)
ctx.Request.Header.Set(originHeaderName, tt.want.origin)
ctx.Request.Header.SetMethod(tt.args.method)
ctx.Response.Header.Set(varyHeaderName, tt.args.vary)
if err := m(ctx); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
wantHeadersValue := map[string]string{
varyHeaderName: tt.want.vary,
allowOriginHeaderName: tt.want.origin,
allowCredentialsHeaderName: tt.want.allowCredentials,
allowHeadersHeaderName: tt.want.allowedHeaders,
allowMethodsHeaderName: tt.want.allowedMethods,
exposeHeadersHeaderName: tt.want.exposedHeaders,
maxAgeHeaderName: tt.want.allowMaxAge,
}
for headerName, want := range wantHeadersValue {
got := string(ctx.Response.Header.Peek(headerName))
if got != want {
t.Errorf("Header: %s == %s, want %s", headerName, got, want)
}
}
})
}
}
func Test_cors_isAllowedOrigin(t *testing.T) {
allowedOrigins := []string{"https://other.domain.test", "https://cors.test"}
origin := allowedOrigins[0]
if allowed := isAllowedOrigin(allowedOrigins, origin); !allowed {
t.Errorf("Origin == %s, must be allowed", origin)
}
origin = "other"
if allowed := isAllowedOrigin(allowedOrigins, origin); allowed {
t.Errorf("Origin == %s, must not be allowed", origin)
}
allowedOrigins = []string{"*"}
if allowed := isAllowedOrigin(allowedOrigins, origin); !allowed {
t.Errorf("Origin == %s, must be allowed", origin)
}
}
| true |
15f69c449cd80606773287993fe15a6722041d30
|
Go
|
MatthewGuo7/study
|
/gotest/srcddd/domain/aggregates/Member.go
|
UTF-8
| 545 | 2.515625 | 3 |
[] |
no_license
|
[] |
no_license
|
package aggregates
import (
"srcddd/domain/models"
"srcddd/repos"
)
type Member struct {
User *models.UserModel
Log *models.UserLogModel
userRepo repos.IUserRepo
userLogRepo repos.IUserLogRepo
}
func NewMember(user *models.UserModel, log *models.UserLogModel, userRepo repos.IUserRepo, userLogRepo repos.IUserLogRepo) *Member {
return &Member{User: user, Log: log, userRepo: userRepo, userLogRepo: userLogRepo}
}
func (m *Member) Create() error {
err := m.userRepo.SaveUser(m.User)
if nil != err {
return err
}
return nil
}
| true |
96ac81680ea2456b8ba275511b4454a01d0a1381
|
Go
|
vchatchai/go201
|
/restful/http-rest-client.go
|
UTF-8
| 1,144 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package restful
import (
"fmt"
resty "gopkg.in/resty.v1"
)
const WEB_SERVICE_HOME string = "http://localhost:8080"
func getEmployeesClient() {
response, err := resty.R().Get(WEB_SERVICE_HOME + "/employees")
if err != nil {
panic(err)
}
fmt.Println(string(response.Body()))
}
func postEmployeeClient() {
response, err := resty.R().
SetHeader("Content-Type", "application/json").
SetBody(Employee{Id: "03", LastName: "Vichai"}).
Post(WEB_SERVICE_HOME + ":" + "/employee/add")
if err != nil {
panic(err)
}
fmt.Println(string(response.Body()))
}
func updateEmployeeClient() {
reponse, err := resty.R().
SetHeader("Content-Type", "application/json").
SetBody(Employee{Id: "03", FirstName: "Chatchai", LastName: "Vichai"}).
Put(WEB_SERVICE_HOME + ":" + "/employee/update")
if err != nil {
panic(err)
}
fmt.Println(string(reponse.Body()))
}
func deleteEmployeeClient() {
response, err := resty.R().
SetHeader("Content-Type", "application/json").
SetBody(Employee{Id: "2"}).
Delete(WEB_SERVICE_HOME + ":" + "/employee/delete")
if err != nil {
panic(err)
}
fmt.Println(string(response.Body()))
}
| true |
eef8611023f307a0b4ba3effa05ea1d7d06c9e4e
|
Go
|
DQNEO/go-samples
|
/myctf/main.go
|
UTF-8
| 198 | 2.921875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
var MyFlag bool = true
func fail() {
panic("FAIL")
}
func ok() {
fmt.Print("OK\n")
}
func main() {
fmt.Print("hello\n")
if MyFlag {
fail()
} else {
ok()
}
}
| true |
9afb17d0e813a0018157a9699925aaad8bfcabfd
|
Go
|
krzysztofreczek/chi-opencensus-tracing
|
/middleware/decorators.go
|
UTF-8
| 1,469 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package middleware
import (
"bytes"
"io"
"net/http"
)
type responseWriterDecorator struct {
buff bytes.Buffer
statusCode int
w http.ResponseWriter
}
func (d *responseWriterDecorator) Flush() {
if w, ok := d.w.(http.Flusher); ok {
w.Flush()
}
}
func decorateResponseWriter(w http.ResponseWriter) *responseWriterDecorator {
return &responseWriterDecorator{
buff: bytes.Buffer{},
w: w,
}
}
func (d *responseWriterDecorator) Header() http.Header {
return d.w.Header()
}
func (d *responseWriterDecorator) Write(bytes []byte) (int, error) {
_, _ = d.buff.Write(bytes)
return d.w.Write(bytes)
}
func (d *responseWriterDecorator) WriteHeader(statusCode int) {
d.statusCode = statusCode
d.w.WriteHeader(statusCode)
}
func (d *responseWriterDecorator) Payload() []byte {
return d.buff.Bytes()
}
func (d *responseWriterDecorator) StatusCode() int {
return d.statusCode
}
type requestBodyDecorator struct {
bodyBytes []byte
body io.ReadCloser
}
func decorateRequestBody(r *http.Request) *requestBodyDecorator {
if r.Body == nil {
return nil
}
return &requestBodyDecorator{
body: r.Body,
}
}
func (d *requestBodyDecorator) Read(p []byte) (int, error) {
n, err := d.body.Read(p)
for i := 0; i < n; i++ {
d.bodyBytes = append(d.bodyBytes, p[i])
}
return n, err
}
func (d *requestBodyDecorator) Close() error {
return d.body.Close()
}
func (d *requestBodyDecorator) Payload() []byte {
return d.bodyBytes
}
| true |
67665e54e5002a96c8d5f50c94aa296827b8c485
|
Go
|
ruohone/nacos-client-go
|
/httpproxy/request.go
|
UTF-8
| 3,642 | 2.78125 | 3 |
[] |
no_license
|
[] |
no_license
|
package httpproxy
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httptrace"
"net/url"
"strings"
)
type Request struct {
req *http.Request
client *Client
err error
}
func (r *Request) SetUrl(l string) *Request {
u, err := url.Parse(l)
if err != nil {
r.err = err
return r
}
r.req.URL = u
r.req.Host = u.Host
return r
}
func (r *Request) Get(url string) *Request {
if r.req.Method == "" {
r.req.Method = http.MethodGet
}
return r.SetUrl(url)
}
func (r *Request) Post(url string) *Request {
if r.req.Method == "" {
r.req.Method = http.MethodPost
}
return r.SetUrl(url)
}
func (r *Request) WithJsonBody(v interface{}) *Request {
r.WithHeader("Content-Type", "application/json")
if v != nil {
var data []byte
switch vv := v.(type) {
case []byte:
data = vv
case json.RawMessage:
data = vv
case string:
data = []byte(vv)
default:
var err error
data, err = json.Marshal(v)
if err != nil {
r.err = err
}
}
if len(data) > 0 {
return r.WithBody(bytes.NewReader(data))
}
}
return r
}
func (r *Request) WithFormBody(body url.Values) *Request {
r.WithHeader("Content-Type", "application/x-www-form-urlencoded")
return r.WithBody(strings.NewReader(body.Encode()))
}
func (r *Request) WithBody(body io.Reader) *Request {
rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
rc = ioutil.NopCloser(body)
}
r.req.Body = rc
if body != nil {
switch v := body.(type) {
case *bytes.Buffer:
r.req.ContentLength = int64(v.Len())
buf := v.Bytes()
r.req.GetBody = func() (io.ReadCloser, error) {
rd := bytes.NewReader(buf)
return ioutil.NopCloser(rd), nil
}
case *bytes.Reader:
r.req.ContentLength = int64(v.Len())
snapshot := *v
r.req.GetBody = func() (io.ReadCloser, error) {
rd := snapshot
return ioutil.NopCloser(&rd), nil
}
case *strings.Reader:
r.req.ContentLength = int64(v.Len())
snapshot := *v
r.req.GetBody = func() (io.ReadCloser, error) {
rd := snapshot
return ioutil.NopCloser(&rd), nil
}
default:
}
if r.req.GetBody != nil && r.req.ContentLength == 0 {
r.req.Body = http.NoBody
r.req.GetBody = func() (io.ReadCloser, error) { return http.NoBody, nil }
}
}
return r
}
func (r *Request) WithRequestID(requestID string) *Request {
return r.WithHeader("X-Request-Id", requestID)
}
func (r *Request) WithCookie(c *http.Cookie) *Request {
r.req.AddCookie(c)
return r
}
func (r *Request) WithQuery(k, v string) *Request {
if k != "" && v != "" {
q := r.req.URL.Query()
q.Set(k, v)
r.req.URL.RawQuery = q.Encode()
}
return r
}
func (r *Request) WithQuerys(querys url.Values) *Request {
if len(querys) > 0 {
q := r.req.URL.Query()
for k, vv := range querys {
for _, v := range vv {
q.Add(k, v)
}
}
r.req.URL.RawQuery = q.Encode()
}
return r
}
func (r *Request) WithTrace(trace *httptrace.ClientTrace) *Request {
if trace != nil {
ctx := httptrace.WithClientTrace(r.req.Context(), trace)
r.req = r.req.WithContext(ctx)
}
return r
}
func (r *Request) WithHeader(k, v string) *Request {
if k != "" && v != "" {
r.req.Header.Set(k, v)
}
return r
}
func (r *Request) Build() (*http.Request, error) {
if r.err != nil {
return nil, r.err
}
return r.req, nil
}
func (r *Request) Execute() *Response {
req, err := r.Build()
if err != nil {
return &Response{nil, err}
}
return r.client.Do(req)
}
func (r *Request) ExecuteAsJson(v interface{}) error {
rsp := r.Execute()
return rsp.ToJson(v)
}
func (r *Request) ExecuteAsString() (string, error) {
rsp := r.Execute()
return rsp.ToString()
}
| true |
5cd517d75edd71ea80fe84a5a06bc9a1ee4da22e
|
Go
|
emaxerrno/claire-protorpc
|
/go/protorpc/codec.go
|
UTF-8
| 1,646 | 2.890625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
[
"BSD-2-Clause"
] |
permissive
|
package claire_protorpc
import (
"encoding/binary"
"fmt"
"hash/adler32"
"io"
"code.google.com/p/goprotobuf/proto"
)
func Encode(msg *RpcMessage) ([]byte, error) {
payload, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
wire := make([]byte, 8+len(payload))
// size
binary.BigEndian.PutUint32(wire, uint32(4+len(payload)))
// checksum
checksum := adler32.Checksum(payload)
binary.BigEndian.PutUint32(wire[4:], checksum)
// payload
if copy(wire[8:], payload) != len(payload) {
panic("What the hell")
}
return wire, nil
}
func Send(w io.Writer, msg *RpcMessage) error {
wire, err := Encode(msg)
if err != nil {
return err
}
n, err := w.Write(wire)
if err != nil {
return err
} else if n != len(wire) {
return fmt.Errorf("Incomplete write %d of %d bytes", n, len(wire))
}
return nil
}
func Decode(r io.Reader) (msg *RpcMessage, err error) {
header := make([]byte, 4)
_, err = io.ReadFull(r, header)
if err != nil {
return
}
length := binary.BigEndian.Uint32(header)
if length > 64*1024*1024 {
err = fmt.Errorf("Invalid length %d", length)
return
}
payload := make([]byte, length)
_, err = io.ReadFull(r, payload)
if err != nil {
return
}
checksum := adler32.Checksum(payload[4:])
if checksum != binary.BigEndian.Uint32(payload[:4]) {
err = fmt.Errorf("Wrong checksum")
return
}
message = new(RpcMessage)
err = proto.Unmarshal(payload[4:], msg)
return
}
| true |
40cc8993236bf121c0628669ae5b635bf4620f2c
|
Go
|
SheldonZheng/LeetCode
|
/DesignAuthenticationManager.go
|
UTF-8
| 915 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
type AuthenticationManager struct {
mp map[string]int
ttl int
}
func Constructor(timeToLive int) AuthenticationManager {
return AuthenticationManager{map[string]int{},timeToLive}
}
func (this *AuthenticationManager) Generate(tokenId string, currentTime int) {
this.mp[tokenId] = currentTime
}
func (this *AuthenticationManager) Renew(tokenId string, currentTime int) {
if v,ok := this.mp[tokenId];ok && v + this.ttl > currentTime {
this.mp[tokenId] = currentTime
}
}
func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int {
res := 0
for _,t := range this.mp {
if t + this.ttl > currentTime {
res++
}
}
return res
}
/**
* Your AuthenticationManager object will be instantiated and called as such:
* obj := Constructor(timeToLive);
* obj.Generate(tokenId,currentTime);
* obj.Renew(tokenId,currentTime);
* param_3 := obj.CountUnexpiredTokens(currentTime);
*/
| true |
f649dc705630ab8a538953f25b8ef33002375787
|
Go
|
Alice52/go-tutorial
|
/tutorials/cn.edu.ntu.awesome/test/monkey/op_test.go
|
UTF-8
| 664 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package monkey
import (
"reflect"
"strings"
"testing"
"bou.ke/monkey"
"cn.edu.ntu.awesome/test/monkey/lib"
)
func TestMyFunc(t *testing.T) {
// 对 varys.GetInfoByUID 进行打桩
monkey.Patch(lib.GetInfoByUID, func(int64) (*lib.UserInfo, error) {
return &lib.UserInfo{Name: "liwenzhou"}, nil
})
ret := MyFunc(123)
if !strings.Contains(ret, "liwenzhou") {
t.Fatal()
}
}
func TestUserMethod(t *testing.T) {
var u = &User{
Name: "q1mi",
Birthday: "1990-12-20",
}
// 为对象方法打桩
monkey.PatchInstanceMethod(reflect.TypeOf(u), "CalcAge", func(*User) int {
return 18
})
ret := u.CalcAge()
if ret != 18 {
t.Fatal()
}
}
| true |
c4078389b706c0c69a574566f7c02d094880dd9b
|
Go
|
xmn-services/rod-network
|
/domain/transfers/piastres/expenses/expense.go
|
UTF-8
| 3,656 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package expenses
import (
"encoding/json"
"time"
"github.com/xmn-services/rod-network/libs/cryptography/pk/signature"
"github.com/xmn-services/rod-network/libs/entities"
"github.com/xmn-services/rod-network/libs/hash"
)
type expense struct {
immutable entities.Immutable
from []hash.Hash
to hash.Hash
signatures []signature.RingSignature
remaining *hash.Hash
}
func createExpenseFromJSON(ins *jsonExpense) (Expense, error) {
hashAdapter := hash.NewAdapter()
hsh, err := hashAdapter.FromString(ins.Hash)
if err != nil {
return nil, err
}
from := []hash.Hash{}
for _, oneStr := range ins.From {
oneFrom, err := hashAdapter.FromString(oneStr)
if err != nil {
return nil, err
}
from = append(from, *oneFrom)
}
to, err := hashAdapter.FromString(ins.To)
if err != nil {
return nil, err
}
ringSigAdapter := signature.NewRingSignatureAdapter()
signatures := []signature.RingSignature{}
for _, oneSigStr := range ins.Signatures {
sig, err := ringSigAdapter.ToSignature(oneSigStr)
if err != nil {
return nil, err
}
signatures = append(signatures, sig)
}
builder := NewBuilder().Create().
WithHash(*hsh).
From(from).
To(*to).
WithSignatures(signatures).
CreatedOn(ins.CreatedOn)
if ins.Remaining != "" {
remaining, err := hashAdapter.FromString(ins.Remaining)
if err != nil {
return nil, err
}
builder.WithRemaining(*remaining)
}
return builder.Now()
}
func createExpense(
immutable entities.Immutable,
from []hash.Hash,
to hash.Hash,
signatures []signature.RingSignature,
) Expense {
return createExpenseInternally(immutable, from, to, signatures, nil)
}
func createExpenseWithRemaining(
immutable entities.Immutable,
from []hash.Hash,
to hash.Hash,
signatures []signature.RingSignature,
remaining *hash.Hash,
) Expense {
return createExpenseInternally(immutable, from, to, signatures, remaining)
}
func createExpenseInternally(
immutable entities.Immutable,
from []hash.Hash,
to hash.Hash,
signatures []signature.RingSignature,
remaining *hash.Hash,
) Expense {
out := expense{
immutable: immutable,
from: from,
to: to,
signatures: signatures,
remaining: remaining,
}
return &out
}
// Hash returns the hash
func (obj *expense) Hash() hash.Hash {
return obj.immutable.Hash()
}
// From returns the from hash
func (obj *expense) From() []hash.Hash {
return obj.from
}
// To returns the to hash
func (obj *expense) To() hash.Hash {
return obj.to
}
// CreatedOn returns the creation time
func (obj *expense) CreatedOn() time.Time {
return obj.immutable.CreatedOn()
}
// Signatures returns the signatures
func (obj *expense) Signatures() []signature.RingSignature {
return obj.signatures
}
// HasRemaining returns true if there is a remaining hash, false otherwise
func (obj *expense) HasRemaining() bool {
return obj.remaining != nil
}
// Remaining returns the remaining hash, if any
func (obj *expense) Remaining() *hash.Hash {
return obj.remaining
}
// MarshalJSON converts the instance to JSON
func (obj *expense) MarshalJSON() ([]byte, error) {
ins := createJSONExpenseFromExpense(obj)
return json.Marshal(ins)
}
// UnmarshalJSON converts the JSON to an instance
func (obj *expense) UnmarshalJSON(data []byte) error {
ins := new(jsonExpense)
err := json.Unmarshal(data, ins)
if err != nil {
return err
}
pr, err := createExpenseFromJSON(ins)
if err != nil {
return err
}
insExpense := pr.(*expense)
obj.immutable = insExpense.immutable
obj.from = insExpense.from
obj.to = insExpense.to
obj.signatures = insExpense.signatures
obj.remaining = insExpense.remaining
return nil
}
| true |
5ee2d5554bc1a0ee85c80efa77fdd393f27c7c31
|
Go
|
iswarm/goclangstudy
|
/kimGo.go
|
UTF-8
| 2,978 | 2.53125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
import "os"
import "log"
import "bytes"
import "path/filepath"
//import "github.com/ethereum/go-ethereum/log"
import "github.com/urfave/cli"
//import "github.com/ethereum/go-ethereum/ethdb"
import (
//"github.com/ethereum/go-ethereum/log"
//"github.com/ethereum/go-ethereum/metrics"
"github.com/syndtr/goleveldb/leveldb"
//"github.com/syndtr/goleveldb/leveldb/errors"
//"github.com/syndtr/goleveldb/leveldb/filter"
//"github.com/syndtr/goleveldb/leveldb/iterator"
//"github.com/syndtr/goleveldb/leveldb/opt"
//"github.com/syndtr/goleveldb/leveldb/util"
)
func main(){
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "lang",
Value:"english",
Usage: "language for the greeting",
},
cli.StringFlag{
Name:"levelDb",
Value: "",
Usage:"learning to call the api of level-db",
},
cli.StringFlag{
Name:"openFile",
Value:"",
Usage:"open the default file",
},
}
app.Action = func(c *cli.Context) error {
name :="Nefertiti"
if c.NArg() >0 {
name = c.Args().Get(0)
}
if c.String("lang") == "spanish" {
fmt.Println("Hola", name)
} else if c.String("openFile") == "openFile"{
file, err := os.Open("/Users/mac/goclangstudy/README.md")
if err != nil {
log.Fatal(err)
}
data:=make([]byte, 1000)
count,err:=file.Read(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("read %d bytes: %q\n", count, data[:count])
var (
buf bytes.Buffer
logger = log.New(&buf, "logger: ", log.Lshortfile)
)
logger.Print("Hello, log file!\n")
fmt.Print(&buf)
fmt.Print("filepath.Base(os.Args[0]) = \n", filepath.Base(os.Args[0]))
} else if c.String("levelDb") == "levelDb" {
//db *leveldb.DB
db,err := leveldb.OpenFile("/Users/mac/goclangstudy", nil)
defer db.Close()
if err != nil {
fmt.Print("Can not open database file")
}
err = db.Put([]byte("productCode"), []byte("01010112132"), nil)
if err != nil {
fmt.Print("Can not put database file")
}
data, err := db.Get([]byte("productCode"),nil)
if err != nil {
fmt.Print("Can not get database file")
}
fmt.Print("data = \n", string(data[:]) )
err = db.Delete([]byte("productCode"), nil)
if err != nil {
fmt.Print("Can not delete database file")
}
}
return nil
}
app.Run(os.Args)
}
| true |
7077a96a7301fc220d37db480da6122e9b0dbe76
|
Go
|
vogo/goalg
|
/tree/rbtree/rbtree.go
|
UTF-8
| 13,877 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2020 [email protected]. All rights reserved.
// a red-black tree implement
// the node only contains pointers to left/right child, not for the parent, for saving storage space for large tree.
package rbtree
import (
"sync"
"github.com/vogo/goalg/compare"
)
// Color node color
type Color bool
func (c Color) String() string {
if c {
return "red"
}
return "black"
}
// Position tree path position, left or right.
type Position bool
const (
Red = Color(true)
Black = Color(false)
Left = Position(true)
Right = Position(false)
)
// Node the node of red-Black tree.
type Node struct {
Item compare.Lesser
Left, Right *Node
Color Color
}
// Black a node is black if nil or its color is black.
func (n *Node) Black() bool {
return n == nil || n.Color == Black
}
// Red a node is red if nil or its color is red.
func (n *Node) Red() bool {
return n == nil || n.Color == Red
}
// LeftBlack the left child of a node is black if nil or its color is black.
func (n *Node) LeftBlack() bool {
return n.Left == nil || n.Left.Color == Black
}
// LeftRed the left child of a node is black if not nil and its color is black.
func (n *Node) LeftRed() bool {
return n.Left != nil && n.Left.Color == Red
}
// RightBlack the right child of a node is black if nil or its color is black.
func (n *Node) RightBlack() bool {
return n.Right == nil || n.Right.Color == Black
}
// RightRed the right child of a node is black if not nil and its color is black.
func (n *Node) RightRed() bool {
return n.Right != nil && n.Right.Color == Red
}
// RBTree red-black tree
type RBTree struct {
Node *Node
lock sync.RWMutex
stack *stack
}
// New create a new red-black tree
func New() *RBTree {
return &RBTree{
lock: sync.RWMutex{},
Node: nil,
stack: newStack(nil),
}
}
// LeftRotate left rotate a node.
func LeftRotate(n *Node) *Node {
r := n.Right
if r == nil {
return n
}
n.Right = r.Left
r.Left = n
return r
}
// RightRotate right rotate a node.
func RightRotate(n *Node) *Node {
l := n.Left
if l == nil {
return n
}
n.Left = l.Right
l.Right = n
return l
}
// Add add one key/value node in the tree, replace that if exist
func (t *RBTree) Add(item compare.Lesser) {
t.lock.Lock()
defer t.lock.Unlock()
t.Node = addTreeNode(t.stack, t.Node, item)
}
// Find node
func (t *RBTree) Find(key compare.Lesser) interface{} {
t.lock.RLock()
defer t.lock.RUnlock()
return Find(t.Node, key)
}
// Delete delete node, return the value of deleted node
func (t *RBTree) Delete(key compare.Lesser) (ret interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
t.stack.init(t.Node)
t.Node, ret = deleteTreeNode(t.stack, t.Node, key)
t.stack.reset()
return ret
}
// addTreeNode add a tree node
func addTreeNode(stack *stack, node *Node, item compare.Lesser) *Node {
stack.init(node)
defer stack.reset()
if node == nil {
// case 1: new root
return &Node{
Item: item,
Color: Black,
}
}
for node != nil {
switch {
case item.Less(node.Item):
stack.push(node, Left)
node = node.Left
case node.Item.Less(item):
stack.push(node, Right)
node = node.Right
default:
node.Item = item
return stack.root()
}
}
stack.bindChild(&Node{
Item: item,
Color: Red,
})
addTreeNodeBalance(stack)
root := stack.root()
root.Color = Black
return root
}
// addTreeNodeBalance balance the tree after adding a node
// the pre condition is the child of current stack is red
func addTreeNodeBalance(stack *stack) {
for stack.index > 0 {
p := stack.node()
// case 2: P is black, balance finish
if p.Color == Black {
return
}
// P is red
pp := stack.parent()
// case 1: reach the root
if pp == nil {
return
}
s := stack.sibling()
// case 3: P is red, S is red, PP is black
// execute: set P,S to black, PP to red
// result: black count through PP is not change, continue balance on parent of PP
if s != nil && s.Color == Red {
p.Color = Black
s.Color = Black
pp.Color = Red
stack.pop().pop()
continue
}
// case 4: P is red, S is black, PP is black, the position of N and P are diff.
// execute: rotate up the red child
// result: let match the case 5.
pos, ppos := stack.position(), stack.parentPosition()
if pos != ppos {
if pos == Left {
p = RightRotate(p)
pp.Right = p
} else {
p = LeftRotate(p)
pp.Left = p
}
}
// case 5: P is red, S is black, PP is black, the position of N and P are the same.
// execute: set P to black, PP to red, and rotate P up
// result: black count through P will not change, balance finish.
p.Color = Black
pp.Color = Red
var ppn *Node
if ppos == Left {
ppn = RightRotate(pp)
} else {
ppn = LeftRotate(pp)
}
stack.pop().pop().bindChild(ppn)
return
}
}
// AddNode add new key/value, return the new root node.
// this method add node and balance the tree recursively, not using loop logic.
func AddNode(root *Node, item compare.Lesser) *Node {
return AddNewNode(root, &Node{
Item: item,
})
}
// AddNewNode add new node, return the new root node.
func AddNewNode(root *Node, node *Node) *Node {
// set the new node to red
node.Color = Red
root = addOneNode(root, Left, node)
// reset root color
root.Color = Black
return root
}
// addOneNode recursively down to leaf, and add the new node to the leaf,
// then rebuild the tree from the leaf to root.
// the main purpose is reduce two linked red nodes and keep the black count balance.
//
// code comment use the following terms:
// - N as the balance node
// - L as the left child of N
// - R as the right child of N
// - P as the parent of N
// - LL as the left child of left child of N
// - RR as the right child of right child of N
func addOneNode(node *Node, pos Position, one *Node) *Node {
// case 1: first node
if node == nil {
return one
}
if one.Item.Less(node.Item) {
node.Left = addOneNode(node.Left, Left, one)
// case 2: L is black means it's already balance.
if node.Left.Color == Black {
return node
}
if node.Color == Red {
// case 3: L is red, N is red, N is right child of P
// execute: right rotate up the L
// result: the black count through L,N will not change, but let it match the case 4
if pos == Right {
node = RightRotate(node)
}
// case 4: L is red, N is red, N is left child of P
// execute: nothing
// result: it's the case 5 of PP
return node
}
if node.Left.Left != nil && node.Left.Left.Color == Red {
// case 5: N is black, L is red, LL is red
// execute: right rotate N, and make LL to black
// result: black count through N is not change, while that through LL increase 1, tree is now balance.
node = RightRotate(node)
node.Left.Color = Black
}
return node
}
if node.Item.Less(one.Item) {
node.Right = addOneNode(node.Right, Right, one)
// case 2: R is black means it's already balance
if node.Right.Color == Black {
return node
}
if node.Color == Red {
if pos == Left {
// case 3: R is red, N is red, N is left child of P
// execute: left rotate up the R
// result: the black count through R,N will not change, but let it match the case 4
node = LeftRotate(node)
}
// case 4: R is red, N is red, N is right child of P
// execute: nothing
// result: it's the case 5 of PP
return node
}
// case 5: N is black, R is red, RR is red
// execute: left rotate N, and make RR to black
// result: black count through N is not change, while that through RR increase 1, tree is now balance.
if node.Right.Right != nil && node.Right.Right.Color == Red {
node = LeftRotate(node)
node.Right.Color = Black
}
return node
}
// case 6: find the exists node, just replace the old value with the new
node.Item = one.Item
return node
}
// Find find the value of a key.
func Find(node *Node, item compare.Lesser) compare.Lesser {
for node != nil {
switch {
case item.Less(node.Item):
node = node.Left
case node.Item.Less(item):
node = node.Right
default:
return node.Item
}
}
return nil
}
// Delete delete a node.
// return the new root node, and the value of the deleted node.
// the new root node will be nil if no node exists in the tree after deleted.
// the deleted node value will be nil if not found.
func Delete(node *Node, item compare.Lesser) (n *Node, ret interface{}) {
if node == nil {
return nil, nil
}
return deleteTreeNode(newStack(node), node, item)
}
// deleteTreeNode delete a node.
// return the new root node, and the value of the deleted node.
// the new root node will be nil if no node exists in the tree after deleted.
// the deleted node value will be nil if not found.
func deleteTreeNode(stack *stack, node *Node, item compare.Lesser) (*Node, interface{}) {
root := node
var ret interface{}
// find the node
FOR:
for node != nil {
switch {
case item.Less(node.Item):
stack.push(node, Left)
node = node.Left
case node.Item.Less(item):
stack.push(node, Right)
node = node.Right
default:
ret = node.Item
break FOR
}
}
// not find
if node == nil {
return root, nil
}
var inorderSuccessor *Node
// find the inorder successor
if node.Right != nil {
stack.push(node, Right)
inorderSuccessor = node.Right
for inorderSuccessor.Left != nil {
stack.push(inorderSuccessor, Left)
inorderSuccessor = inorderSuccessor.Left
}
node.Item = inorderSuccessor.Item
node.Item = inorderSuccessor.Item
node = inorderSuccessor
}
// get the child of node
c := node.Left
if c == nil {
c = node.Right
}
// N has no child
if c == nil {
// delete N
stack.bindChild(nil)
if node.Color == Red {
return root, ret
}
deleteTreeNodeBalance(stack)
root = stack.root()
if root != nil {
root.Color = Black
}
return root, ret
}
// N has one next
// then copy key/value from next to N
node.Item = c.Item
// delete the next
node.Left = nil
node.Right = nil
// N has diff color with next
if node.Color != c.Color {
// set color of N to black
node.Color = Black
return root, ret
}
// the color of N and next are both Black
deleteTreeNodeBalance(stack)
root.Color = Black
return root, ret
}
// deleteTreeNodeBalance balance the tree after deleting.
// code comment use the following terms:
// - N as the balance node
// - P as the father of N
// - PP as the grand father of N
// - S as the sibling of N
// - SL as the left child of S
// - SR as the right child of S
func deleteTreeNodeBalance(stack *stack) {
var (
p, pp, s *Node
pos, ppos Position
)
// case 1: reach the root.
// execute: nothing.
// result: balance finish.
for stack.index > 0 {
p, pp, s = stack.node(), stack.parent(), stack.childSibling()
pos, ppos = stack.position(), stack.parentPosition()
// case 2: S is red.
// execute: rotate S up as the PP of N, and exchange the color of P and S.
// result: the black number not change, but N has a black sibling now.
if s.Color == Red {
p.Color, s.Color = s.Color, p.Color
// np is original S
var np *Node
if pos == Left {
np = LeftRotate(p)
s = p.Right
} else {
np = RightRotate(p)
s = p.Left
}
// insert np in stack
stack.insertBefore(np, pos)
if ppos == Left {
pp.Left = np
} else {
pp.Right = np
}
// reset PP (original S)
pp = np
}
// now S is black.
if s.LeftBlack() && s.RightBlack() {
// case 3: color of P, S, SL, SR are all Black.
// execute: set S to red.
// result: the path through S will reduce one black, and the left and right of P now balance,
// set N to p, and continue execute balance.
if p.Black() {
s.Color = Red
stack.pop()
continue
}
// case4: S, SL, SR are black, P is red.
// execute: exchange the color of S and P.
// result: add one black on the path through N, while that is not change for path through S, balance finish.
p.Color, s.Color = s.Color, p.Color
return
}
// now SL and SR has diff color
if pos == Left {
// case 5: N is left child of P, S is black, SL is red, SR is black.
// execute: right rotate on S, then exchange color of SL(parent of S now) and S.
// result: N has a new black sibling S(original SL), and S has a red right child SR(original S),
// while the black count through S will not change.
if s.LeftRed() {
s = RightRotate(s)
s.Color, s.Right.Color = s.Right.Color, s.Color
p.Right = s
}
// case6: N is left child of P, S is black, SL is black, SR is red.
// execute: set SR to black, left rotate P, the exchange the color of P and S.
// result: S is now the parent of P, the black count through N increase 1,
// the black count through S keep the same,
// balance finish.
s.Right.Color = Black
p.Color, s.Color = s.Color, p.Color
p = LeftRotate(p)
if ppos == Left {
pp.Left = p
} else {
pp.Right = p
}
return
}
// case 5: N is right child of P, S is black, SL is black, SR is red.
// execute: left rotate on S, then exchange color of SR(parent of S now) and S.
// result: N has a new black sibling S(original SR), and S has a red left child SL(original S),
// while the black count through S will not change.
if s.RightRed() {
s = LeftRotate(s)
s.Color, s.Left.Color = s.Left.Color, s.Color
p.Left = s
}
// case6: N is right child of P, S is black, SL is red, SR is black.
// execute: set SL to black, right rotate P, the exchange the color of P and S.
// result: S is now the parent of P, the black count through N increase 1,
// the black count through S keep the same,
// balance finish.
s.Left.Color = Black
p = RightRotate(p)
if ppos == Left {
pp.Left = p
} else {
pp.Right = p
}
p.Color, s.Color = s.Color, p.Color
return
}
}
| true |
1bab73926651fa8ba163022dae2c6636596c1332
|
Go
|
cthayer/pc-proxy
|
/cmd/pc-proxy/config_test.go
|
UTF-8
| 5,247 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"net/http/httptest"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"github.com/cthayer/pc-proxy/internal/config"
"github.com/cthayer/pc-proxy/internal/proxy"
)
func TestLoadConfigFile(t *testing.T) {
configFile := filepath.Join("..", "..", "test", "config")
configFileExts := []string{".json", ".hcl"}
for _, ext := range configFileExts {
confFile := configFile + ext
if err := LoadConfigFile(confFile, func(conf *config.Config) {}); err != nil {
t.Errorf("Failed to load "+strings.ToUpper(ext)+" configuration file. (%s) %v", confFile, err)
}
conf := config.GetConfig()
if conf.TLS.Enabled {
t.Errorf("expected TLS.Enabled to be false, got %v", conf.TLS.Enabled)
}
if conf.TLS.Cert != "" {
t.Errorf("expected TLS.Cert to be empty, got %v", conf.TLS.Cert)
}
if conf.TLS.Key != "" {
t.Errorf("expected TLS.Key to be empty, got %v", conf.TLS.Key)
}
if len(conf.Rules) != 1 {
t.Errorf("expected 1 rule, got %v", len(conf.Rules))
}
access, aOk := conf.Rules[0]["access"]
if !aOk {
t.Errorf("config rule missing 'access' property")
}
if access != "block" {
t.Errorf("expected %v, got %v", "block", access)
}
pattern, pOk := conf.Rules[0]["pattern"]
if !pOk {
t.Errorf("config rule missing 'pattern' property")
}
if pattern != "" {
t.Errorf("expected %v, got %v", "", pattern)
}
passwordBypass, pbOk := conf.Rules[0]["passwordBypass"]
if !pbOk {
t.Errorf("config rule missing 'passwordBypass' property")
}
if !passwordBypass.(bool) {
t.Errorf("expected %v, got %v", true, passwordBypass)
}
ty, tOk := conf.Rules[0]["type"]
if !tOk {
t.Errorf("config rule missing 'type' property")
}
if ty != "host" {
t.Errorf("expected %v, got %v", "host", ty)
}
}
}
func TestLoadConfigFileAllowRulesPatternEscape(t *testing.T) {
configFile := filepath.Join("..", "..", "test", "config-allow-rules-pattern-escape")
configFileExts := []string{".hcl"}
for _, ext := range configFileExts {
confFile := configFile + ext
if err := LoadConfigFile(confFile, func(conf *config.Config) {}); err != nil {
t.Errorf("Failed to load "+strings.ToUpper(ext)+" configuration file. (%s) %v", confFile, err)
}
conf := config.GetConfig()
if conf.TLS.Enabled {
t.Errorf("expected TLS.Enabled to be false, got %v", conf.TLS.Enabled)
}
if conf.TLS.Cert != "" {
t.Errorf("expected TLS.Cert to be empty, got %v", conf.TLS.Cert)
}
if conf.TLS.Key != "" {
t.Errorf("expected TLS.Key to be empty, got %v", conf.TLS.Key)
}
if len(conf.Rules) != 17 {
t.Errorf("expected 17 rules, got %v", len(conf.Rules))
}
access, aOk := conf.Rules[0]["access"]
if !aOk {
t.Errorf("config rule missing 'access' property")
}
if access != "allow" {
t.Errorf("expected %v, got %v", "allow", access)
}
pattern, pOk := conf.Rules[0]["pattern"]
if !pOk {
t.Errorf("config rule missing 'pattern' property")
}
if pattern != "zoom\\.us" {
t.Errorf("expected %v, got %v", "zoom\\.us", pattern)
}
passwordBypass, pbOk := conf.Rules[0]["passwordBypass"]
if !pbOk {
t.Errorf("config rule missing 'passwordBypass' property")
}
if !passwordBypass.(bool) {
t.Errorf("expected %v, got %v", true, passwordBypass)
}
ty, tOk := conf.Rules[0]["type"]
if !tOk {
t.Errorf("config rule missing 'type' property")
}
if ty != "host" {
t.Errorf("expected %v, got %v", "host", ty)
}
}
}
func TestLoadConfigFileWithProxy(t *testing.T) {
pxy := proxy.New()
patternReplaceRegex := regexp.MustCompile(`[^-\w\d.]`)
configFile := filepath.Join("..", "..", "test", "config-allow-rules-pattern-escape")
configFileExt := ".hcl"
confFile := configFile + configFileExt
if err := LoadConfigFile(confFile, pxy.LoadConfig); err != nil {
t.Errorf("Failed to load "+strings.ToUpper(configFileExt)+" configuration file. (%s) %v", confFile, err)
}
conf := config.GetConfig()
if len(pxy.Rules) != len(conf.Rules) {
t.Errorf("expected %v rules, got %v", len(conf.Rules), len(pxy.Rules))
}
for i, r := range pxy.Rules {
if string(r.Access) != conf.Rules[i]["access"] {
t.Errorf("expected %v, got %v", conf.Rules[i]["access"], r.Access)
}
if r.Pattern != conf.Rules[i]["pattern"] {
t.Errorf("expected %v, got %v", conf.Rules[i]["pattern"], r.Pattern)
}
if r.PasswordBypass != conf.Rules[i]["passwordBypass"] {
t.Errorf("expected %v, got %v", conf.Rules[i]["passwordBypass"], r.PasswordBypass)
}
if string(r.Type) != conf.Rules[i]["type"] {
t.Errorf("expected %v, got %v", conf.Rules[i]["type"], r.Type)
}
target := "https://" + patternReplaceRegex.ReplaceAllString(r.Pattern, "") + "/foo/bar"
req := httptest.NewRequest("GET", target, nil)
bypassCache := map[string]map[string]time.Duration{}
match, allowed := r.Match(req, httptest.NewRecorder(), "test", &bypassCache, time.Minute)
if !match {
t.Errorf("expected r %v to match %v", r.Pattern, target)
}
if conf.Rules[i]["access"] == "allow" && !allowed {
t.Errorf("expected allowed to be true, got %v", allowed)
}
if conf.Rules[i]["access"] == "block" && allowed {
t.Errorf("expected allowed to be false, got %v", allowed)
}
}
}
| true |
048c4c1b4b7a679d8349d513eaa2ae01a039df66
|
Go
|
camolezi/GolangService
|
/src/services/user_service.go
|
UTF-8
| 599 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package services
import (
"github.com/camolezi/MicroservicesGolang/src/model"
"github.com/camolezi/MicroservicesGolang/src/services/data"
"golang.org/x/crypto/bcrypt"
)
//CreateNewUser is the service that creates new users - for now only
func CreateNewUser(user model.User, password string) error {
//Maybe we want to do this asynchronous
hash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
if err != nil {
return err
}
user.HashedPassword = hash
access := data.CreateDataAccess()
err = access.CreateUser(user)
if err != nil {
return err
}
//Created
return nil
}
| true |
f91530e6943e202973f19f73ee6000b58f621c60
|
Go
|
DeveloperJim/bk-bcs
|
/bcs-services/bcs-project/internal/component/client_test.go
|
UTF-8
| 2,103 | 2.75 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"BSD-3-Clause",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"BSD-3-Clause",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
* 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 component
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/parnurzeal/gorequest"
"github.com/stretchr/testify/assert"
)
// ref: https://github.com/parnurzeal/gorequest/blob/develop/gorequest_test.go
func TestRequest(t *testing.T) {
// 预制值
case1_empty := "/"
case2_set_header := "/set_header"
retData := "hello world"
// 设置一个 http service
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != "GET" {
t.Errorf("Expected method %q; got %q", "GET", r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
w.Write([]byte(retData))
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
}
}))
defer ts.Close()
// 发起请求
req := gorequest.SuperAgent{
Url: ts.URL,
Method: "GET",
}
timeout := 10
body, err := Request(req, timeout, "", map[string]string{})
assert.Nil(t, err)
assert.Equal(t, body, retData)
Request(req, timeout, "", map[string]string{"API-Key": "fookey"})
}
| true |
148083f8a7f3b7578b23f15e095b537f884e6231
|
Go
|
tkmagesh/IBM-Go-Aug-2021
|
/03-functions/04-demo.go
|
UTF-8
| 496 | 3.8125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
fn := func() {
fmt.Println("fn is invoked")
}
exec(fn)
process(add, 100, 200)
process(subtract, 200, 500)
}
func process(msg string, fn func(int, int) int, x, y int) {
fmt.Println("Adding 2 numbers")
result := fn(x, y)
fmt.Println("Result:", result)
}
func exec(fn func()) {
fmt.Println("Executing fn")
fn()
fmt.Println("Finished executing fn")
}
func add(x, y int) int {
return x + y
}
func subtract(x, y int) int {
return x - y
}
| true |
c8aee5c863ac802a4626971effbdbcf7aeeb8ebf
|
Go
|
dimnsk/tribonacci
|
/src/app/api_test.go
|
UTF-8
| 930 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"net/http"
"testing"
"io/ioutil"
"time"
)
func TestTribHandler(t *testing.T) {
go startServer()
client := &http.Client{
Timeout: 1 * time.Second,
}
// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
// pass 'nil' as the third parameter.
r, _ := http.NewRequest("GET", "http://localhost:8081/v1/trib/10", nil)
resp, err := client.Do(r)
if err != nil {
t.Fatal(err)
}
// Check the status code is what we expect.
if status := resp.StatusCode; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
// Check the response body is what we expect.
expected := `{"result":"44"}`
bodyBytes, err := ioutil.ReadAll(resp.Body)
bodyString := string(bodyBytes)
if bodyString != expected {
t.Errorf("handler returned unexpected body: got %v want %v",
bodyString, expected)
}
}
| true |
6272ea2ad502c9daf19ce4485d73d85509a59eef
|
Go
|
trunghai95/chaos-game-go
|
/main.go
|
UTF-8
| 1,797 | 2.75 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"time"
"github.com/fogleman/gg"
)
var (
configFile = flag.String("configFile", "config.json", "Config JSON file name")
)
func main() {
flag.Parse()
cfg := &Config{}
err := cfg.LoadFromJsonFile(*configFile)
if err != nil {
log.Fatalf("Error loading config file [%v]: %v", *configFile, err)
}
if len(cfg.Transformations) == 0 {
log.Println("No transformation")
return
}
transform(cfg)
}
func transform(cfg *Config) {
rand.Seed(time.Now().UnixNano())
// Prepare the list of all trace points
points := []Point{cfg.StartPoint}
x, y := cfg.StartPoint.X, cfg.StartPoint.Y
maxX, maxY := x, y
minX, minY := x, y
for i := 0; i < cfg.LoopCount; i++ {
r := rand.Float64()
t := cfg.Transformations[len(cfg.Transformations)-1]
for j := 0; j < len(cfg.Transformations); j++ {
if cfg.cumProb[j] >= r {
t = cfg.Transformations[j]
break
}
}
newX := t.A*x + t.B*y + t.E
newY := t.C*x + t.D*y + t.F
x, y = newX, newY
maxX = max(maxX, x)
maxY = max(maxY, y)
minX = min(minX, x)
minY = min(minY, y)
points = append(points, Point{x, y})
}
log.Printf("Finish preparing points, x[%v;%v], y[%v;%v]", minX, maxX, minY, maxY)
szX := (maxX - minX) * cfg.Draw.Scale
szY := (maxY - minY) * cfg.Draw.Scale
if szX > 2000 || szY > 2000 {
log.Printf("Too large, can't draw: %vx%v", szX, szY)
return
}
ctx := gg.NewContext(rnd(szX), rnd(szY))
for _, p := range points {
ctx.DrawPoint((p.X-minX)*cfg.Draw.Scale, (p.Y-minY)*cfg.Draw.Scale, cfg.Draw.PointSize)
}
ctx.SetRGB(cfg.Draw.PointColor[0], cfg.Draw.PointColor[1], cfg.Draw.PointColor[2])
ctx.Fill()
outputFile := fmt.Sprintf("%v.png", time.Now().UnixNano())
err := ctx.SavePNG(outputFile)
if err != nil {
log.Fatal(err)
}
}
| true |
2604416a98d8cc3a44da10f802443cbd2af0b920
|
Go
|
mrbkiter/golang-exercise
|
/src/cli/commands/hugo.go
|
UTF-8
| 364 | 2.890625 | 3 |
[] |
no_license
|
[] |
no_license
|
package commands
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
var RootCmd = &cobra.Command{
Use: "hugo",
Short: "Hugo Short description",
Long: `Hogo Longer description..
feel free to use a few lines here.
`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
fmt.Println(strings.Join(args, " "))
},
}
| true |
a2ffa896409b0c769e9785f56d730491ddf430f0
|
Go
|
poudel/golearngo
|
/if_statements.go
|
UTF-8
| 567 | 3.875 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"math"
)
func sqrt (x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
func pow (x, n, lim float64) float64 {
// variables declared by the short statement are only in scope
// until the end of the `if`
// they are also available in relevant `else` blocks
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
return lim
}
func main () {
fmt.Println(sqrt(2))
fmt.Println(sqrt(-4))
fmt.Println(
"POWER",
pow(3, 2, 10),
pow(3, 3, 20),
)
}
| true |
0102a0ba935419551e793f5b6704d4cfc3d66928
|
Go
|
febelery/grpcdemo
|
/simple/client/main.go
|
UTF-8
| 653 | 2.53125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"context"
"google.golang.org/grpc"
"log"
pb "rpcdemo/simple/proto"
"time"
)
const Address string = "localhost:8000"
func main() {
conn, err := grpc.Dial(Address, grpc.WithInsecure())
if err != nil {
log.Fatalf("net.Connect err: %v", err)
}
defer conn.Close()
grpcClient := pb.NewSimpleClient(conn)
req := pb.SimpleRequest{Data: "grpc"}
ctx := context.Background()
clientDeadline := time.Now().Add(3 * time.Second)
ctx, cancel := context.WithDeadline(ctx, clientDeadline)
defer cancel()
res, err := grpcClient.Route(ctx, &req)
if err != nil {
log.Fatalf("Call Route err: %v", err)
}
log.Println(res)
}
| true |
8498681faec2d22ea6194ad6001bd129b7085bcc
|
Go
|
tebrizetayi/go-rabbitmq
|
/consumer.go
|
UTF-8
| 654 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"github.com/streadway/amqp"
)
func main() {
fmt.Println("Consumer Application")
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
fmt.Println(err)
panic(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
fmt.Println(err)
panic(err)
}
defer ch.Close()
msgs,err:=ch.Consume("TestQueue","",true,false,false,false,nil)
//forever:=make(chan bool)
go func() {
for d:=range msgs{
fmt.Printf("Received Messages:%s\n",d.Body)
}
}()
fmt.Println("Succesfully connected to pur RabbitMQ instance")
fmt.Println("[*] -waiting for messages")
fmt.Scanln()
}
| true |
daba54d485697aef90f246a177d7feb03779c664
|
Go
|
stjordanis/neat-1
|
/decoder/hyperneat.go
|
UTF-8
| 4,859 | 2.546875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
[
"BSD-2-Clause"
] |
permissive
|
/*
Copyright (c) 2015 Brian Hummer ([email protected]), All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution. Neither the name of the nor the names of its
contributors may be used to endorse or promote products derived from this software without
specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package decoder
import (
"fmt"
"math"
"github.com/rqme/neat"
)
// Special case: 1 layer of nodes in this case, examine nodes to separate out "vitural layers" by neuron type
// othewise connect every neuron in one layer to the subsequent layer
type HyperNEATSettings interface {
SubstrateLayers() []SubstrateNodes // Substrate definitions
WeightRange() float64 // Weight range for new connections
}
type HyperNEAT struct {
HyperNEATSettings
CppnDecoder neat.Decoder
}
// Outputs 0..len(substrate layers) = weights. if len(outputs) = 2* that number, second set is activation function, 3rd is bias connection? Need flags for these
// n = number of layers - 1
// first n = weights
// flags for bias oututs = 1 or 2 meaning use outputs starting at 1*n or 2*n
// activation, too.
func (d *HyperNEAT) Decode(g neat.Genome) (p neat.Phenome, err error) {
// Validate the number of inputs and outputs
if err = d.validate(g); err != nil {
return
}
// Decode the CPPN
var cppn neat.Phenome
cppn, err = d.CppnDecoder.Decode(g)
if err != nil {
return nil, err
}
// Create a new Substrate
layers := d.SubstrateLayers()
ncnt := len(layers[0])
ccnt := 0
for i := 1; i < len(layers); i++ {
ncnt += len(layers[i])
ccnt += len(layers[i]) * len(layers[i-1])
}
s := &Substrate{
Nodes: make([]SubstrateNode, 0, ncnt),
Conns: make([]SubstrateConn, 0, ccnt),
}
// Add the nodes to the substrate
i := 0
for _, l := range layers {
// TODO: Should I sort the nodes by position in the network?
for j, n := range l {
l[j].id = i
s.Nodes = append(s.Nodes, n)
i += 1
}
}
// Create connections
var outputs []float64 // output from the Cppn
wr := d.WeightRange()
for l := 1; l < len(layers); l++ {
for _, src := range layers[l-1] {
for _, tgt := range layers[l] {
outputs, err = cppn.Activate(append(src.Position, tgt.Position...))
if err != nil {
return nil, err
}
w := math.Abs(outputs[l-1])
if w > 0.2 {
s.Conns = append(s.Conns, SubstrateConn{
Source: src.id,
Target: tgt.id,
Weight: math.Copysign((w-0.2)*wr/0.8, outputs[l-1]),
})
}
}
}
}
// Return the new network
var net neat.Network
net, err = s.Decode()
if err != nil {
return nil, err
}
p = Phenome{g, net}
return
}
func (d *HyperNEAT) validate(g neat.Genome) error {
var icnt, ocnt int
for _, n := range g.Nodes {
if n.NeuronType == neat.Input {
icnt += 1
} else if n.NeuronType == neat.Output {
min, max := n.ActivationType.Range()
found := false
switch {
case math.IsNaN(min), math.IsNaN(max):
found = true
case min >= 0:
found = true
}
if found {
return fmt.Errorf("Invalid activation type for output: %s [%f, %f]", n.ActivationType, min, max)
}
ocnt += 1
}
}
layers := d.SubstrateLayers()
cnt := len(layers[0][0].Position)
for i, l := range layers {
for j, n := range l {
if len(n.Position) != cnt {
return fmt.Errorf("Inconsistent position length in substrate layer %d node %d. Expected %d but found %d.", i, j, cnt, len(n.Position))
}
}
}
if cnt*2 < icnt {
return fmt.Errorf("Insufficient number of inputs to decode substrate. Need %d but have %d", cnt*2, icnt)
}
if ocnt < len(layers)-1 {
return fmt.Errorf("Insufficient number of outputs to decode substrate. Need %d but have %d", len(layers)-1, ocnt)
}
return nil
}
| true |
8bc2f5a7586e99cfb5a357acb730d53b9b7d33d6
|
Go
|
tutumagi/codewar
|
/LastDigitOfHugeNumber.go
|
UTF-8
| 1,120 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"math/big"
)
// 1 2 3 4 5 6 7 8 9 0
//0 0 0 0 0 0 0 0 0 0 1
//1 1 1 1 1 1 1 1 1 1 1
//2 2 4 8 6 2 4 8 6 2 1
//3 3 9 7 1 3 9 7 1 3 1
//4 4 6 4 6 4 6 4 6 4 1
//5 5 5 5 5 5 5 5 5 5 1
//6 6 6 6 6 6 6 6 6 6 1
//7 7 9 3 1 7 9 3 1 7 1
//8 8 4 2 6 8 4 2 6 8 1
//9 9 1 9 1 9 1 9 1 9 1
// 底数:尾数顺序
var predefine = map[int][]int{
0: {0},
1: {1},
2: {2, 4, 8, 6},
3: {3, 9, 7, 1},
4: {4, 6},
5: {5},
6: {6},
7: {7, 9, 3, 1},
8: {8, 4, 2, 6},
9: {9, 1},
}
// https://www.codewars.com/kata/5518a860a73e708c0a000027/train/go
// https://brilliant.org/wiki/finding-the-last-digit-of-a-power/
// https://www.youtube.com/watch?v=k7rm55Sw-SE
func LastDigitWithHugeNumber(as []int) int {
if len(as) == 0 {
return 1
}
result := big.NewInt(1)
four := big.NewInt(4)
t1 := new(big.Int)
tmp := new(big.Int)
for i := len(as) - 1; i >= 0; i-- {
if result.Cmp(four) >= 0 {
result = result.Mod(result, four)
result = result.Add(result, four)
}
t1.SetInt64(int64(as[i]))
result = tmp.Exp(t1, result, nil)
}
return int(result.Mod(result, big.NewInt(10)).Int64())
}
| true |
bd128483e9e20c426d7a4f64900f8518f4321dad
|
Go
|
zhoujinxinbaozi/algo_golang
|
/src/com/zjx/leetcode/11_maxArea/Main.go
|
UTF-8
| 1,562 | 3.8125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
/**
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
示例:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
solution:
两个指针,分别指向头left和尾right,取min(height[left], height[right]), min的值与right-left想乘。与全局的result的进行对比。
if height[left] < height[right] left 右移,直到找到大于当前值得下标停止
else right 左移,直到找到大于当前值得下标停止
*/
func main() {
fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
}
func maxArea(height []int) int {
result := 0
left := 0
right := len(height) - 1
leftHight := 0
rightHight := 0
for {
if left >= right {
break
}
var minHight int
leftHight = height[left]
rightHight = height[right]
if leftHight < rightHight {
minHight = leftHight
} else {
minHight = rightHight
}
if (right-left)*minHight > result {
result = (right - left) * minHight
}
if leftHight < rightHight {
for {
if left >= right {
break
}
left++
if height[left] > leftHight {
break
}
}
} else {
for {
if left >= right {
break
}
right--
if height[right] > rightHight {
break
}
}
}
}
return result
}
| true |
ceaeb5fb1d8404013455acc711ac84df64a5777a
|
Go
|
akshay111meher/mychain
|
/controller/createAccount.go
|
UTF-8
| 935 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package controller
import(
. "../crypto"
"fmt"
"os"
"io/ioutil"
// "crypto/ecdsa"
// "reflect"
"encoding/json"
"encoding/hex"
)
func CreateAccount(name string) bool{
privateKeyBytes,publicKeyBytes:= GenerateKeys()
path:= "../accounts/"+name+".json"
var _, err = os.Stat(path)
// create file if not exists
if os.IsNotExist(err) {
var file, err = os.Create(path)
if isError(err) { }
defer file.Close()
}else{
return false
}
fmt.Println("==> done creating file", path)
return saveAccount(path,privateKeyBytes,publicKeyBytes)
}
func saveAccount(path string, privateKey, publicKey []byte) bool{
key := Key{hex.EncodeToString(privateKey[:]),hex.EncodeToString(publicKey[:])}
keyBytes,_ := json.Marshal(key)
err := ioutil.WriteFile(path, keyBytes, 0644)
if isError(err){
fmt.Println("==> failed writing to file")
return false
}else{
fmt.Println("==> done writing to file")
return true;
}
}
| true |
5fe76e338a112ee31fd80f0ed56a37dc94b132fc
|
Go
|
engelsjk/gmartini
|
/example/main.go
|
UTF-8
| 870 | 2.765625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"image"
"math"
"os"
"github.com/engelsjk/gmartini"
)
func main() {
file, err := os.Open("data/fuji.png")
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
terrain, err := gmartini.DecodeElevation(img, "mapbox", true)
if err != nil {
panic(err)
}
martini, err := gmartini.New(gmartini.OptionGridSize(513))
if err != nil {
panic(err)
}
tile, err := martini.CreateTile(terrain)
if err != nil {
panic(err)
}
mesh := tile.GetMesh(gmartini.OptionMaxError(30))
fmt.Printf("gmartini\n")
fmt.Printf("terrain: %.0f+1 x %.0f+1\n", math.Sqrt(float64(len(terrain)))-1, math.Sqrt(float64(len(terrain)))-1)
fmt.Printf("max error: %d\n", 30)
fmt.Printf("mesh vertices: %d\n", mesh.NumVertices)
fmt.Printf("mesh triangles: %d\n", mesh.NumTriangles)
}
| true |
a44db204de363a539afc2ebb91350b3dae8d0053
|
Go
|
romshark/messenger-sim
|
/service/messaging/simulator/get_messages.go
|
UTF-8
| 1,298 | 2.75 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package simulator
import (
"context"
"fmt"
"github.com/romshark/messenger-sim/messenger/event"
"github.com/romshark/messenger-sim/service/messaging"
)
func (s *Simulator) GetMessages(
ctx context.Context,
conversationID event.ConversationID,
afterID *event.MessageID,
limit int,
) ([]*messaging.Message, error) {
if limit < 1 {
return nil, fmt.Errorf("invalid limit (%d)", limit)
}
s.lock.RLock()
defer s.lock.RUnlock()
c, ok := s.conversationsByID[conversationID]
if !ok {
return nil, nil
}
var slice []*message
if afterID == nil {
// Read at begin
if limit > len(c.messages) {
slice = c.messages
} else {
slice = c.messages[:limit]
}
} else {
// Read after certain message
indexOf := func() int {
for i, m := range c.messages {
if m.ID == *afterID {
return i
}
}
return -1
}()
if indexOf < 0 {
return nil, fmt.Errorf(
"message (%s) not found",
afterID.String(),
)
}
indexOf++
if indexOf >= len(c.messages) {
return nil, nil
}
tail := indexOf + limit
if tail > len(c.messages) {
tail = len(c.messages)
}
slice = c.messages[indexOf:tail]
}
messages := make([]*messaging.Message, len(slice))
for i, msg := range slice {
m := msg.Message
messages[i] = &m
}
return messages, nil
}
| true |
d34f6a2f2b186edfbf9b2b71f999388b88fa2ff6
|
Go
|
bixlabs/authentication
|
/database/user/sqlite/sqlite.go
|
UTF-8
| 4,949 | 2.875 | 3 |
[] |
no_license
|
[] |
no_license
|
package sqlite
import (
"fmt"
"github.com/bixlabs/authentication/authenticator/database/user"
"github.com/bixlabs/authentication/authenticator/structures"
"github.com/bixlabs/authentication/database/mappers"
"github.com/bixlabs/authentication/database/model"
"github.com/bixlabs/authentication/tools"
"github.com/caarlos0/env"
"github.com/jinzhu/gorm"
"github.com/sirupsen/logrus"
)
type sqliteStorage struct {
db *gorm.DB
Name string `env:"AUTH_SERVER_DATABASE_NAME" envDefault:"sqlite.s3db"`
User string `env:"AUTH_SERVER_DATABASE_USER" envDefault:"admin"`
Password string `env:"AUTH_SERVER_DATABASE_PASSWORD" envDefault:"secure-password"`
Salt string `env:"AUTH_SERVER_DATABASE_SALT" envDefault:"salted"`
}
func NewSqliteStorage() (user.Repository, func()) {
db := sqliteStorage{}
err := env.Parse(&db)
contextLogger := db.getLogger()
if err != nil {
contextLogger.WithError(err).Panic("parsing the env variables for the db failed")
}
contextLogger.Info("env variables for db were parsed")
closeDB := db.initialize()
return db, closeDB
}
func (storage *sqliteStorage) initialize() func() {
contextLogger := storage.getLogger()
contextLogger.Info("db is initializing")
db := openDatabase(storage)
db.AutoMigrate(&model.User{})
contextLogger.Info("db was automigrated")
storage.db = db
return func() {
if err := storage.db.Close(); err != nil {
contextLogger.Error("there was an error closing the connection with the db")
}
}
}
func openDatabase(storage *sqliteStorage) *gorm.DB {
contextLogger := storage.getLogger()
db, err := gorm.Open("sqlite3", storage.getConnectionString())
if err != nil {
contextLogger.WithError(err).Panic("there was an error initializing the db connection")
}
contextLogger.Info("db connection was initialized")
storage.db = db
return db
}
func (storage sqliteStorage) getConnectionString() string {
// TODO: I'm not sure the authentication is working as we expect here, I'm sure in development this is not
// working but when creating a build it might be working as expected we need to ensure this later.
return fmt.Sprintf("file:%s?_auth&_auth_user=%s&_auth_pass=%s&_auth_crypt=ssha512&_auth_salt=%s",
storage.Name, storage.User, storage.Password, storage.Salt)
}
func (storage sqliteStorage) Create(user structures.User) (structures.User, error) {
modelForCreate := mappers.UserToDatabaseModel(user)
transaction := storage.db.Begin()
if err := transaction.Create(&modelForCreate).Error; err != nil {
transaction.Rollback()
return structures.User{}, err
}
if err := transaction.Commit().Error; err != nil {
return structures.User{}, err
}
return storage.Find(user.Email)
}
func (storage sqliteStorage) Find(email string) (structures.User, error) {
var account model.User
if err := storage.db.First(&account, "email = ?", email).Error; err != nil {
return structures.User{}, err
}
return mappers.DatabaseModelToUser(account), nil
}
func (storage sqliteStorage) IsEmailAvailable(email string) (bool, error) {
_, err := storage.Find(email)
if gorm.IsRecordNotFoundError(err) {
return true, nil
}
return false, err
}
func (storage sqliteStorage) GetHashedPassword(email string) (string, error) {
account, err := storage.Find(email)
if err != nil {
return "", err
}
return account.Password, nil
}
func (storage sqliteStorage) ChangePassword(email, newPassword string) error {
transaction := storage.db.Begin()
if err := transaction.Model(&model.User{Email: email}).Update("password", newPassword).Error; err != nil {
transaction.Rollback()
return err
}
return transaction.Commit().Error
}
func (storage sqliteStorage) UpdateResetToken(email, resetToken string) error {
transaction := storage.db.Begin()
if err := transaction.Model(&model.User{Email: email}).Update("reset_token", resetToken).Error; err != nil {
transaction.Rollback()
return err
}
return transaction.Commit().Error
}
func (storage sqliteStorage) Delete(user structures.User) error {
transaction := storage.db.Begin()
if err := transaction.Delete(&user).Error; err != nil {
transaction.Rollback()
return err
}
return transaction.Commit().Error
}
func (storage sqliteStorage) Update(email string, updateAttrs structures.User) (structures.User, error) {
user, err := storage.Find(email)
if err != nil {
return structures.User{}, err
}
transaction := storage.db.Begin()
modelForUpdate := mappers.UserToDatabaseModel(user)
modelUpdateAttrs := mappers.UserToDatabaseModel(updateAttrs)
if err := transaction.Model(&modelForUpdate).Update(modelUpdateAttrs).Error; err != nil {
transaction.Rollback()
return structures.User{}, err
}
if err := transaction.Commit().Error; err != nil {
return structures.User{}, err
}
return mappers.DatabaseModelToUser(modelForUpdate), nil
}
func (storage sqliteStorage) getLogger() *logrus.Entry {
return tools.Log().WithField("storage", "sqlite")
}
| true |
20f0057021c1708f9133f3baf4ebc11bb1a1ffb7
|
Go
|
Potewo/CashRegisterChecker
|
/save_test.go
|
UTF-8
| 4,272 | 3.203125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"github.com/google/go-cmp/cmp"
"io/ioutil"
"os"
"reflect"
"testing"
)
var (
teststring string = "hogefuga"
testfilename string = "currentFile"
)
func TestCurrentFileSuccess(t *testing.T) {
oldFile, err := ioutil.ReadFile(testfilename)
if err != nil {
t.Fatalf("failed to open file by ioutil %#v", err)
}
file, err := os.Create(testfilename)
if err != nil {
t.Fatalf("failed to open file by os%#v", err)
}
defer func() {
err = file.Close()
if err != nil {
t.Logf("failed to close file")
}
file, err := os.Create(testfilename)
if err != nil {
t.Logf("failed to reopen file")
}
file.Write(oldFile)
t.Logf("Writed %#v", string(oldFile))
err = file.Close()
if err != nil {
t.Logf("failed to close file")
}
}()
_, err = file.WriteString(teststring)
if err != nil {
t.Fatalf("failed to Writing file")
}
filename, err := currentFile()
if err != nil {
t.Logf("failed to get currentFile")
t.Fatal(err)
}
if filename != teststring {
t.Logf("except: %#v | but: %#v", teststring, filename)
t.Fatalf("failed to test: not same")
}
}
func TestGetHeaderTest(t *testing.T) {
testFileName := "test.csv"
exceptValue := []string{"a", "b", "c"}
file, err := os.Create(testFileName)
defer func() {
if err := os.Remove(testFileName); err != nil {
t.Log("failed to remove test file")
t.Fatal(err)
}
}()
if err != nil {
t.Log("failed to create new file for test")
t.Fatal(err)
}
defer file.Close()
file.WriteString("a,b,c\n1,3,4")
headerNames, err := getHeader(testFileName)
t.Logf("header: %#v", headerNames)
if !reflect.DeepEqual(headerNames, exceptValue) {
t.Fatalf("not same except: %#v but: %#v", exceptValue, headerNames)
}
}
func TestAppendToFile(t *testing.T) {
testFileName := "test.csv"
expectedValue := "abc\ndef\n"
oldString := "abc\n"
file, err := os.Create(testFileName)
if err != nil {
t.Log("failed to create new file for test")
t.Fatal(err)
}
defer func() {
file.Close()
if err := os.Remove(testFileName); err != nil {
t.Log("failed to remove test file")
t.Fatal(err)
}
}()
file.WriteString(oldString)
err = appendToFile(testFileName, "def")
if err != nil {
t.Logf("failed to run appendToFile()")
t.Fatal(err)
}
if err = file.Close(); err != nil {
t.Log("failed to close file")
t.Fatal(err)
}
file, err = os.Open(testFileName)
if err != nil {
t.Log("failed to close file")
t.Fatal(err)
}
bytes, err := ioutil.ReadAll(file)
t.Logf("output: %#v", string(bytes))
if string(bytes) != expectedValue {
t.Fatal("not same")
}
}
func TestCheckHeader(t *testing.T) {
expectedValue := []string{"a", "b", "c"}
file, err := os.Create("test.txt")
defer file.Close()
if err != nil {
t.Fatal("failed to create a new file")
}
file.WriteString("a,b,c\n1,2,3")
file.Close()
success, err := checkHeader("test.txt", expectedValue)
if !success {
t.Fatal("not same")
}
err = os.Remove("test.txt")
if err != nil {
t.Fatal(err)
}
}
func TestConvertJsonToMap(t *testing.T) {
jsonStr := `{"a":1, "b":2, "c":5}`
expectedValue := map[string]interface{}{
"a": float64(1),
"b": float64(2),
"c": float64(5),
}
mapData, err := convertJsonToMap(jsonStr)
if err != nil {
t.Logf("failed to converting json to a map")
t.Fatal(err)
}
if !reflect.DeepEqual(mapData, expectedValue) {
t.Logf(cmp.Diff(expectedValue, mapData))
t.Fatal("not same")
}
}
func TestConvertJsonToStruct(t *testing.T) {
jsonStrToPass := `{
"date": "1975-08-19T23:15:30.000Z",
"caches": [
{
"initialValue": 50,
"unitCost": 1,
"name": "1yen",
"value": 0
}, {
"initialValue": 50,
"unitCost": 5,
"name": "5yen",
"value": 0
}, {
"initialValue": 50,
"unitCost": 10,
"name": "10yen",
"value": 0
}
],
"sales": 0,
"otherServices": [{
"unitCost": 500,
"n": 0,
"isPositive": true,
"name": "Rabies"
}],
"unpaids": [0],
"ins": [0],
"outs": [0],
"others": [0]
}`
s, err := convertJsonToStruct(jsonStrToPass)
if err != nil {
t.Logf("failed to convert")
t.Fatal(err)
}
t.Logf("%#v", s)
}
| true |
cb387bdc83f3287f5b2d51f452ccbeabc3fdc5d4
|
Go
|
libnux/goenv
|
/main.go
|
UTF-8
| 1,109 | 3.109375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", helloHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
go func() {
fmt.Println("listening on :" + port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
panic(err)
}
}()
port2 := "7070"
go func() {
fmt.Println("listening on :" + port2)
err := http.ListenAndServe(":"+port2, nil)
if err != nil {
panic(err)
}
}()
select {}
}
func helloHandler(res http.ResponseWriter, req *http.Request) {
var sb bytes.Buffer
res.Header().Set("Content-Type", "text/html")
sb.WriteString("Hello,Go!<br><br>")
sb.WriteString("Host=" + req.Host + "<br>")
sb.WriteString("Referer=" + req.Referer() + "<br>")
reqHeader := req.Header
for n, v := range reqHeader {
sb.WriteString(n + "=")
for _, av := range v {
sb.WriteString(av + ",")
}
sb.WriteString("<br>")
}
env := os.Environ()
sb.WriteString("<br><br>System Env Variables<br>===============<br>")
for _, v := range env {
sb.WriteString(v)
sb.WriteString("<br>")
}
res.Write(sb.Bytes())
}
| true |
40682b28dbaeb865d0422374f6dc505ace3c91b2
|
Go
|
akavel/splitsound
|
/mp3cut/mpaframeparser.go
|
UTF-8
| 5,101 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"io"
"mp3agic"
"os"
)
const (
MAX_MPAFRAME_SIZE = 2048
FILTER_MPEG1 = uint32(0x0001)
FILTER_MPEG2 = uint32(0x0002)
FILTER_MPEG25 = uint32(0x0004)
FILTER_LAYER1 = uint32(0x0008)
FILTER_LAYER2 = uint32(0x0010)
FILTER_LAYER3 = uint32(0x0020)
FILTER_32000HZ = uint32(0x0040)
FILTER_44100HZ = uint32(0x0080)
FILTER_48000HZ = uint32(0x0100)
FILTER_MONO = uint32(0x0200)
FILTER_STEREO = uint32(0x0400)
)
type mpaFrameParser struct {
ips io.Reader
junkh *MyCountingJunkHandler
masker, masked uint32
headBuff [4]byte
}
func getMpegFilter(fh *mp3agic.FrameHeader) uint32 {
if fh.Verify() != nil {
return 0
}
switch fh.Version() {
case mp3agic.MPEG_VERSION_1_0:
return FILTER_MPEG1
case mp3agic.MPEG_VERSION_2_0:
return FILTER_MPEG2
case mp3agic.MPEG_VERSION_2_5:
return FILTER_MPEG25
}
return 0
}
func getModeFilter(fh *mp3agic.FrameHeader) uint32 {
if fh.Verify() != nil {
return 0
}
if fh.Channels() == 1 {
return FILTER_MONO
}
return FILTER_STEREO
}
func getSamplingrateFilter(fh *mp3agic.FrameHeader) uint32 {
if fh.Verify() != nil {
return 0
}
switch fh.SampleRate() {
case 32000, 16000, 8000:
return FILTER_32000HZ
case 44100, 22050, 11025:
return FILTER_44100HZ
case 48000, 24000, 12000:
return FILTER_48000HZ
}
return 0
}
func getLayerFilter(fh *mp3agic.FrameHeader) uint32 {
if fh.Verify() != nil {
return 0
}
switch fh.Layer() {
case mp3agic.MPEG_LAYER_1:
return FILTER_LAYER1
case mp3agic.MPEG_LAYER_2:
return FILTER_LAYER2
case mp3agic.MPEG_LAYER_3:
return FILTER_LAYER3
}
return 0
}
func getFilterFor(fh *mp3agic.FrameHeader) uint32 {
return getMpegFilter(fh) | getModeFilter(fh) | getSamplingrateFilter(fh) | getLayerFilter(fh)
}
// TODO: update the comment
/**
* tries to find the next MPEG Audio Frame, loads it into the destination
* buffer (including 32bit header) and returns a FrameHeader object. (If
* destFH is non-null, that object will be used to store the header infos)
* will block until data is available. will throw EOFException of any other
* IOException created by the InputStream object. set filter to 0 or to any
* other value using the FILTER_xxx flags to force a specific frame type.
*/
func (p *mpaFrameParser) getNextFrame(filter uint32, destBuffer []byte, destFH *mp3agic.FrameHeader) (*mp3agic.FrameHeader, os.Error) {
p.setupFilter(filter)
fill(p.headBuff[:], 0)
hbPos := 0
fh := destFH
if fh == nil {
fh = new(mp3agic.FrameHeader)
}
var tmp [1]byte
skipped := -4
for {
readn, err := p.ips.Read(tmp[:])
if readn == 0 && err == os.EOF { // EOF ?
if p.junkh != nil {
for i := 0; i < 4; i++ { // flush headBuff
if skipped >= 0 {
p.junkh.Write(p.headBuff[(hbPos+i)&3])
}
skipped++
}
p.junkh.EndOfJunkBlock()
}
return nil, os.EOF
} else if err != os.EOF {
return nil, err
}
if p.junkh != nil && skipped >= 0 {
p.junkh.Write(p.headBuff[hbPos])
}
p.headBuff[hbPos] = tmp[0]
skipped++
hbPos = (hbPos + 1) & 3
if p.headBuff[hbPos] != 0xFF {
continue // not the beginning of a sync-word
}
header32 := uint32(p.headBuff[hbPos])
for z := 1; z < 4; z++ {
header32 <<= 8
header32 |= uint32(p.headBuff[(hbPos+z)&3])
}
if header32&p.masker != p.masked {
continue // not a frame header
}
*fh = mp3agic.FrameHeader(header32)
if fh.Verify() != nil { // doesn't look like a proper header
continue
}
if filter&FILTER_STEREO != 0 && fh.Channels() != 2 {
continue
}
offs := 0
for ; offs < 4; offs++ {
destBuffer[offs] = p.headBuff[(hbPos+offs)&3]
}
tmp2 := fh.LengthInBytes() - offs
//tmp2 := fh.getFrameSize() - offs;
// FIXME: behaviour when not enough data read (different from Java)
readn, err = p.ips.Read(destBuffer[offs : offs+tmp2])
if readn != tmp2 {
if err != os.EOF {
panic(err)
}
if p.junkh != nil {
readn += 4 // inklusive header
for z := 0; z < readn; z++ {
p.junkh.Write(destBuffer[z] & 0xFF)
}
p.junkh.EndOfJunkBlock()
}
return nil, err
}
if p.junkh != nil {
p.junkh.EndOfJunkBlock()
}
break
}
return fh, nil
}
func (p *mpaFrameParser) setupFilter(filter uint32) {
p.masker = 0xFFE00000
p.masked = 0xFFE00000
switch {
case filter&FILTER_MPEG1 != 0:
p.masker |= 0x00180000
p.masked |= 0x00180000
case filter&FILTER_MPEG2 != 0:
p.masker |= 0x00180000
p.masked |= 0x00100000
}
switch {
case filter&FILTER_LAYER1 != 0:
p.masker |= 0x00060000
p.masked |= 0x00060000
case filter&FILTER_LAYER2 != 0:
p.masker |= 0x00060000
p.masked |= 0x00040000
case filter&FILTER_LAYER3 != 0:
p.masker |= 0x00060000
p.masked |= 0x00020000
}
switch {
case filter&FILTER_32000HZ != 0:
p.masker |= 0x00000C00
p.masked |= 0x00000800
case filter&FILTER_44100HZ != 0:
p.masker |= 0x00000C00
p.masked |= 0x00000000
case filter&FILTER_48000HZ != 0:
p.masker |= 0x00000C00
p.masked |= 0x00000400
}
if filter&FILTER_MONO != 0 {
p.masker |= 0x000000C0
p.masked |= 0x000000C0
}
}
| true |
f823c14fc64458378478474246f3dbfff27a5919
|
Go
|
mokuhara/omochi
|
/app/repository/bizpack.go
|
UTF-8
| 2,375 | 2.765625 | 3 |
[] |
no_license
|
[] |
no_license
|
package repository
import "omochi/app/models"
import "log"
type BizpackRepository struct {}
func (BizpackRepository) Create(bizpack *models.Bizpack) error {
if err := DB.Create(&bizpack).Error; err != nil {
return err
}
return nil
}
//部分更新に対応させてないので追々実装する
func (BizpackRepository) Update(editBizpack *models.Bizpack) error {
bizpack := models.Bizpack{}
if err := DB.Model(&bizpack).Updates(editBizpack).Error; err != nil {
return err
}
return nil
}
// TODO: deleteと合わせてリファクタ
func (BizpackRepository) CheckUserBizpack(userId int64, bizpackId int64) bool {
bizpack := models.Bizpack{}
if err := DB.Where("id = ?", bizpackId).First(&bizpack).Error; err != nil {
return false
}
return bizpack.UserID == userId
}
func (BizpackRepository) Delete(bizpackId int64) error {
bizpack := models.Bizpack{}
if err := DB.Where("id = ?", bizpackId).Delete(&bizpack).Error; err != nil {
return err
}
return nil
}
func (BizpackRepository) GetAll() (*[]models.Bizpack, error) {
var bizpacks []models.Bizpack
if err := DB.Set("gorm:auto_preload", true).Find(&bizpacks).Error; err != nil {
return nil, err
}
return &bizpacks, nil
}
func (BizpackRepository) Find(bizpackId int64) (*models.Bizpack, error){
bizpack := models.Bizpack{}
if err := DB.Set("gorm:auto_preload", true).Where("id = ?", bizpackId).First(&bizpack).Error; err != nil {
return nil, err
}
return &bizpack, nil
}
func (BizpackRepository) GetByUserId(userId int64) (*[]models.Bizpack, error){
bizpacks:= []models.Bizpack{}
log.Println(userId)
if err := DB.Set("gorm:auto_preload", true).Where("user_id = ?", userId).Find(&bizpacks).Error; err != nil {
return nil, err
}
return &bizpacks, nil
}
func (BizpackRepository) GetByBizpackId(bizpackId int64) (*models.Bizpack, error) {
bizpack := models.Bizpack{}
if err := DB.Set("gorm:auto_preload", true).Where("id = ?", bizpackId).First(&bizpack).Error; err != nil {
return nil, err
}
return &bizpack, nil
}
// TODO: 要リファクタ
func (BizpackRepository) GetByUserIDAndBizpackId(userId int64, bizpackId int64) (*models.Bizpack, error) {
bizpack := models.Bizpack{}
if err := DB.Set("gorm:auto_preload", true).Where("id = ? AND user_id = ?", bizpackId, userId).First(&bizpack).Error; err != nil {
return nil, err
}
return &bizpack, nil
}
| true |
773251564732a44c37936f36efc15ece3df2ee90
|
Go
|
NivHamisha/aggregator
|
/utils/helpers.go
|
UTF-8
| 2,912 | 3.203125 | 3 |
[] |
no_license
|
[] |
no_license
|
package utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"reflect"
"strings"
)
type jsonStringData map[string]interface{}
func GetExpensesFromDir(dirName string) ([]Expense, error) {
var allExpenses []Expense
files, err := ioutil.ReadDir(dirName)
if err != nil{
return nil, err
}
for _, file := range files{
fullFilePath := dirName + "/" + file.Name()
fileData, err := ioutil.ReadFile(fullFilePath)
if err != nil {
return nil, err
}
var fileExpense Expense
if err = json.Unmarshal(fileData, &fileExpense); err != nil {
return nil, err
}
allExpenses = append(allExpenses, fileExpense)
}
return allExpenses, nil
}
func ReadQuery(filename string) (GroupByQuery, error) {
queryData, err := ioutil.ReadFile(filename)
if err != nil {
return GroupByQuery{}, err
}
var query GroupByQuery
if err = json.Unmarshal(queryData, &query); err != nil {
return GroupByQuery{}, err
}
return query, nil
}
func IsExpensesEqual(expense1, expense2 *Expense, params []string) bool {
for _,param := range params{
value1, _ := expense1.GetField(param)
value2, _:= expense2.GetField(param)
if value1 != value2{
return false
}
}
return true
}
func ModifyParam(field string) string {
return strings.ToUpper(field[:1]) + field[1:]
}
func GroupBy(expenses []Expense, params []string)([]Expense, error){
if expenses == nil{
return nil, fmt.Errorf("expenses is empty")
}
var groupedExpenses []Expense
lastExpense := expenses[0]
if exists, param := lastExpense.CheckParamsExists(params); !exists {
return nil, fmt.Errorf("param is not exists: %s", param)
}
for _, expense := range expenses[1:]{
if IsExpensesEqual(&lastExpense, &expense, params){
lastExpense.MoneySpent = lastExpense.MoneySpent + expense.MoneySpent
} else {
groupedExpenses = append(groupedExpenses, lastExpense)
lastExpense = expense
}
}
groupedExpenses = append(groupedExpenses, lastExpense)
return groupedExpenses, nil
}
func GetGroupedDataString(groupedData []Expense, query *GroupByQuery)string{
dataJsonString := "["
for _, result:= range groupedData{
resultString := result.GetPrintParamsString(append(query.Params,"moneySpent"))
dataJsonString = dataJsonString + resultString + fmt.Sprintf(",\n")
}
return dataJsonString[:len(dataJsonString)-2] + fmt.Sprintf("]")
}
func GetJsonStringData(groupedData []Expense, query *GroupByQuery)[]jsonStringData{
var jsonData []jsonStringData
newParams := append(query.Params,"moneySpent")
jsonString := map[string]interface{}{}
for _, result:= range groupedData{
for _, param := range newParams {
value,valueType := result.GetField(param)
var floatTest float64
if valueType == reflect.TypeOf(floatTest){
value = math.Round(value.(float64)*100)/100
}
jsonString[param] = value
}
jsonData = append(jsonData, jsonString)
jsonString = map[string]interface{}{}
}
return jsonData
}
| true |
de4138e44342f030f6520ca3bd662070603de9df
|
Go
|
titagaki/peercast-yayp
|
/model/channel.go
|
UTF-8
| 991 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package model
import (
"time"
)
type Channel struct {
ID uint
CID string `gorm:"column:cid;size:32"`
Name string `gorm:"index"`
Bitrate int
ContentType string
Listeners int
Relays int
Age uint
Genre string
Description string
Url string
Comment string
TrackArtist string
TrackTitle string
TrackAlbum string
TrackGenre string
TrackContact string
HiddenListeners bool
TrackerIP string `gorm:"size:53"`
TrackerDirect bool
IsPlaying bool `gorm:"index" json:"-"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
}
type ChannelList []*Channel
func (list ChannelList) HideListeners() ChannelList {
var newList ChannelList
for _, c := range list {
if c.HiddenListeners {
tmp := *c
tmp.Listeners = -1
tmp.Relays = -1
c = &tmp
}
newList = append(newList, c)
}
return newList
}
| true |
cc6850bd60dedc15376d2180dfa2bca57b6af848
|
Go
|
msagheer/libnetwork-plugin
|
/miscellaneous/rest/rest.go
|
UTF-8
| 2,882 | 2.9375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package rest
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
)
type PgRestHandle struct {
Ip_or_host string
Port int
User string
Password string
client_cookies *cookiejar.Jar
httpClient *http.Client
}
func CreatePGRestClient(rest_ip string, rest_Port int, Username string, Password string) *PgRestHandle {
cookies, _ := cookiejar.New(nil)
return &PgRestHandle{
Ip_or_host: rest_ip,
Port: rest_Port,
User: Username,
Password: Password,
client_cookies: cookies,
httpClient: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Jar: cookies,
},
}
}
func RestGet(handle *PgRestHandle, path string) (error, int, []byte) {
req, _ := http.NewRequest("GET", path, nil)
req.Header.Set("Accept", "application/json")
res, err := handle.httpClient.Do(req)
if err != nil {
return fmt.Errorf("Failed to login on PG plat: %v", err), 0, nil
}
// Read body data
body_data, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
return fmt.Errorf("Error reading body data %v", err), 0, nil
}
return nil, res.StatusCode, body_data
}
func RestPost(handle *PgRestHandle, path string, data string) (error, int, []byte) {
req, _ := http.NewRequest("POST", path, bytes.NewBufferString(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
res, err := handle.httpClient.Do(req)
if err != nil {
return fmt.Errorf("Faild to POST: %v", err), 0, nil
}
// Read body data
body_data, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
return fmt.Errorf("Error reading body data %v", err), 0, nil
}
return nil, res.StatusCode, body_data
}
func RestPut(handle *PgRestHandle, path string, data string) (error, int, []byte) {
req, _ := http.NewRequest("PUT", path, bytes.NewBufferString(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
res, err := handle.httpClient.Do(req)
if err != nil {
return fmt.Errorf("Faild to PUT: %v", err), 0, nil
}
// Read body data
body_data, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
return fmt.Errorf("Error reading body data %v", err), 0, nil
}
return nil, res.StatusCode, body_data
}
func RestDelete(handle *PgRestHandle, path string) (error, int, []byte) {
req, _ := http.NewRequest("DELETE", path, nil)
req.Header.Set("Accept", "application/json")
res, err := handle.httpClient.Do(req)
if err != nil {
return fmt.Errorf("Failed to DELETE: %v", err), 0, nil
}
// Read body data
body_data, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
return fmt.Errorf("Error reading body data %v", err), 0, nil
}
return nil, res.StatusCode, body_data
}
| true |
7e637ac85c9dbb3319e05a9601e1982e5c2b2098
|
Go
|
iCodeIN/go-con-study
|
/docker/deadlock/bugs/moby256/archive_test.go
|
UTF-8
| 746 | 2.78125 | 3 |
[] |
no_license
|
[] |
no_license
|
package docker
import (
"io"
"io/ioutil"
"os/exec"
"testing"
"fmt"
)
func TestCmdStreamLargeStderr(t *testing.T) {
// This test checks for deadlock; thus, the main failure mode of this test is deadlocking.
// If we change count=63, then this test case could be passed. If count >= 64, it would be failed.
cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
out, err := CmdStream(cmd)
if err != nil {
t.Fatalf("Failed to start command: " + err.Error())
}
fmt.Println("start call io copy in test")
_, err = io.Copy(ioutil.Discard, out)
fmt.Println("end call io copy in test")
if err != nil {
t.Fatalf("Command should not have failed (err=%s...)", err.Error()[:100])
}
}
| true |
7a8172ce4b2f8ba751645c5dc2da1a6a68ab47cb
|
Go
|
youguanxinqing/Goforit
|
/009/NilMap/main.go
|
UTF-8
| 365 | 3.453125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
var m map[string]int
fmt.Println(m) // map[]
if m == nil {
fmt.Println("m = nil") // 执行
}
if v, ok := m["zhong"]; ok { // 不存报错
fmt.Println(v)
} else {
fmt.Println(v) // 0
}
delete(m, "zhong") // 删除某个键-元素对,正常运行
m["10"] = 10 // 报错,不允许添加键-元素对
}
| true |
d7289a0a3edbff0cc42e89c288ebf6d26067c91b
|
Go
|
rzajac/kml
|
/element.go
|
UTF-8
| 7,331 | 3.328125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package kml
import (
"bytes"
"encoding/xml"
"errors"
)
// Element represents KML element and provides set of methods for easy
// exploration of the KML structure.
type Element struct {
// Start element.
se xml.StartElement
// Element's children.
children []*Element
// Element contents.
// If element has children it is nil.
content xml.CharData
// Offset of the element from the the start of the file.
offset int64
}
// NewElement returns new instance of Element with name and adds child
// elements or attributes to it. NewElement panics if variadic argument
// is not one of xml.Attr or *Element
func NewElement(name string, els ...interface{}) *Element {
xel := &Element{
se: xml.StartElement{
Name: xml.Name{Local: name},
},
}
if err := xel.AddChild(els...); err != nil {
panic(err)
}
return xel
}
// ID returns id attribute value for the element. Returns empty string if id
// attribute does not exist.
func (e *Element) ID() string {
return e.Attribute("id").Value
}
// LocalName returns XML element name.
func (e *Element) LocalName() string {
return e.se.Name.Local
}
// Offset returns byte offset the element starts.
func (e *Element) Offset() int64 {
return e.offset
}
// HasAttribute returns true if element has attribute.
func (e *Element) HasAttribute(name string) bool {
for _, atr := range e.se.Attr {
if atr.Name.Local == name {
return true
}
}
return false
}
// AttributeCnt returns number of attributes the element has.
func (e *Element) AttributeCnt() int {
return len(e.se.Attr)
}
// Attribute returns attribute by name. If attribute does not exist the
// zero value is returned.
func (e *Element) Attribute(name string) xml.Attr {
for _, atr := range e.se.Attr {
if atr.Name.Local == name {
return atr
}
}
return xml.Attr{}
}
// SetAttribute sets element's attribute. If attribute already exists it
// will be overwritten.
func (e *Element) SetAttribute(a xml.Attr) {
// Set if already present.
for i := range e.se.Attr {
if e.se.Attr[i].Name.Local == a.Name.Local {
e.se.Attr[i].Value = a.Value
e.se.Attr[i].Name.Space = a.Name.Space
return
}
}
e.se.Attr = append(e.se.Attr, a)
}
// HasChild returns true if element has a child with local name.
func (e *Element) HasChild(name string) bool {
return e.ChildByName(name) != nil
}
// ChildCnt returns number of child elements of the element.
func (e *Element) ChildCnt() int {
return len(e.children)
}
// ChildAtIdx returns child element at index. Returns nil if index is out of
// bounds.
func (e *Element) ChildAtIdx(index int) *Element {
if index >= len(e.children) || index < 0 {
return nil
}
return e.children[index]
}
// ChildByName returns first child element by local name. Returns nil if
// child does not exist.
func (e *Element) ChildByName(name string) *Element {
for _, ch := range e.children {
if ch.se.Name.Local == name {
return ch
}
}
return nil
}
// ChildByID returns first child element with ID. Returns nil if does not exist.
func (e *Element) ChildByID(id string) *Element {
for _, ch := range e.children {
if ch.ID() == id {
return ch
}
}
return nil
}
// AddChild adds child element(s) to the element.
func (e *Element) AddChild(els ...interface{}) error {
for _, elm := range els {
switch el := elm.(type) {
case xml.Attr:
e.SetAttribute(el)
case *Element:
e.children = append(e.children, el)
default:
return errors.New("expected xml.Attr or *Element")
}
}
return nil
}
// PrependChild prepends one or more child elements.
func (e *Element) PrependChild(els ...interface{}) error {
p := len(els)
if p == 0 {
return nil
}
l := len(e.children)
tmp := make([]*Element, l+p)
copy(tmp[p:], e.children)
e.children = tmp[:0]
if err := e.AddChild(els...); err != nil {
e.children = tmp[p:]
return err
}
e.children = tmp
return nil
}
// RemoveChildren removes all child elements.
func (e *Element) RemoveChildren() {
e.children = nil
}
// RemoveChildAtIdx removes child element at index.
func (e *Element) RemoveChildAtIdx(index int) *Element {
elm := e.ChildAtIdx(index)
if elm == nil {
return nil
}
e.children = append(e.children[:index], e.children[index+1:]...)
return elm
}
// Content returns element's content. It returns empty nil slice if
// element's content is empty or if element is a container for other
// elements.
func (e *Element) Content() []byte {
return e.content
}
// ContentString returns element's content as string. It returns empty string
// if element's content is empty or if element is a container for other
// elements.
func (e *Element) ContentString() string {
return string(e.content)
}
// SetContent sets element's content. It will not set the content if the
// element is a container for other elements (has one or more child elements).
func (e *Element) SetContent(content []byte) {
if len(e.children) > 0 {
return
}
e.content = content
}
// ChildContent is a convenience method returning content of the first child
// matching name or nil if element has no children.
func (e *Element) ChildContent(name string) []byte {
for _, ch := range e.children {
if ch.Attribute(name).Name.Local != name {
return ch.Content()
}
}
return nil
}
func (e *Element) UnmarshalXML(dec *xml.Decoder, se xml.StartElement) error {
if se.Name.Local != e.se.Name.Local {
return ErrUnexpectedElement
}
// Set XML element attributes unless KML root element
// in which case we already did it when creating the element.
if e.se.Name.Local != ElemKML {
e.se.Attr = se.Attr
}
off := dec.InputOffset()
for {
tok, err := dec.Token()
if err != nil {
return err
}
switch el := tok.(type) {
case xml.StartElement:
ch := NewElement(el.Name.Local)
ch.offset = off
if err := ch.UnmarshalXML(dec, el); err != nil {
return err
}
e.children = append(e.children, ch)
case xml.CharData:
e.content = bytes.TrimSpace(el.Copy())
if e.content == nil {
off = dec.InputOffset()
}
case xml.EndElement:
if el == se.End() {
return nil
}
}
}
}
const cdataStart = "<![CDATA["
const cdataEnd = "]]>"
func (e *Element) MarshalXML(enc *xml.Encoder, _ xml.StartElement) error {
// Special case when encoding KLM root element.
// It adds XML prolog as a first line.
if e.se.Name.Local == ElemKML {
proc := xml.ProcInst{
Target: "xml",
Inst: []byte(`version="1.0" encoding="UTF-8"`),
}
if err := enc.EncodeToken(proc); err != nil {
return err
}
if err := enc.EncodeToken(xml.CharData{'\n'}); err != nil {
return err
}
}
// Use CDATA directive for content that need it.
if len(e.content) > 0 && needsCDATA(e.content) {
value := make([]byte, len(cdataStart)+len(cdataEnd)+len(e.content))
copy(value, cdataStart)
copy(value[len(cdataStart):], e.content)
copy(value[len(cdataStart)+len(e.content):], cdataEnd)
cdataWrap := struct {
Value []byte `xml:",innerxml"`
}{
Value: value,
}
if err := enc.EncodeElement(cdataWrap, e.se); err != nil {
return err
}
return nil
}
if err := enc.EncodeToken(e.se); err != nil {
return err
}
if err := enc.EncodeToken(e.content); err != nil {
return err
}
for _, c := range e.children {
if err := enc.EncodeElement(c, e.se); err != nil {
return err
}
}
return enc.EncodeToken(e.se.End())
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.