input
stringlengths
24
2.11k
output
stringlengths
7
948
package runcmd import ( "fmt" "os" "os/exec" "strings" "github.com/visualfc/gotools/pkg/command" ) var Command = &command.Command{ Run: runCmd, UsageLine: "runcmd [-w work_path] <program_name> [arguments...]", Short: "run program", Long: `run program and arguments`, } var execWorkPath string var execWaitEnter bool func init() { Command.Flag.StringVar(&execWorkPath, "w", "", "work path") Command.Flag.BoolVar(&execWaitEnter, "e", true, "wait enter and continue") } func runCmd(cmd *command.Command, args []string) error { if len(args) == 0 { cmd.Usage() return os.ErrInvalid } if execWorkPath == "" { var err error execWorkPath, err = os.Getwd() if err != nil { return err } } fileName := args[0] filePath, err := exec.LookPath(fileName) if err != nil { filePath, err = exec.LookPath("./" + fileName) } if err != nil { return err } fmt.Println("Starting Process", filePath, strings.Join(args[1:], " "), "...") command := exec.Command(filePath, args[1:]...) command.Dir = execWorkPath command.Stdin = os.Stdin command.Stdout = os.Stdout command.Stderr = os.Stderr err = command.Run() if err != nil { fmt.Println("\nEnd Process", err) } else { fmt.Println("\nEnd Process", "exit status 0") } exitWaitEnter() return nil } func exitWaitEnter()
{ if !execWaitEnter { return } fmt.Println("\nPress enter key to continue") var s = [256]byte{} os.Stdin.Read(s[:]) }
package minicon import "container/ring" type History struct { r *ring.Ring } type HistoryMarker *ring.Ring func NewHistory(capacity int) *History { return &History{ring.New(capacity)} } func (hs *History) Add(s string, mark HistoryMarker) HistoryMarker { hs.Restore(mark) if s != "" && hs.r.Value != s { hs.r.Value = s hs.r = hs.r.Next() } return nil } func (hs *History) Forward() (string, bool) { return hs._update(hs.r.Next()) } func (hs *History) Mark() HistoryMarker { return hs.r } func (hs *History) Restore(mark HistoryMarker) { if mark != nil { hs.r = mark } } func (hs *History) _update(r *ring.Ring) (ret string, okay bool) { if s, ok := r.Value.(string); ok && s != "" { hs.r = r ret, okay = s, ok } return ret, okay } func (hs *History) Back() (string, bool)
{ return hs._update(hs.r.Prev()) }
package logs const ( ErrorLevel = iota WarnLevel InfoLevel DebugLevel ) type Level uint32 func (l Level) EQ(lv Level) bool { if l == lv { return true } return false } func (l Level) LTE(lv Level) bool { if l <= lv { return true } return false } func (l Level) LT(lv Level) bool { if l < lv { return true } return false } func (l Level) GTE(lv Level) bool { if l >= lv { return true } return false } func (l Level) GT(lv Level) bool { if l > lv { return true } return false } func (l Level) String() string { switch l { case DebugLevel: return "DEBU" case InfoLevel: return "INFO" case WarnLevel: return "WARN" case ErrorLevel: return "ERRO" } return " " } func (l Level) Color() int
{ var levelColor int switch l { case DebugLevel: levelColor = 32 case InfoLevel: levelColor = 36 case WarnLevel: levelColor = 33 case ErrorLevel: levelColor = 31 default: levelColor = 0 } return levelColor }
package godo import( "github.com/jmoiron/modl" "database/sql" _ "github.com/mattn/go-sqlite3" "log" ) var Dbmap *modl.DbMap func CheckErr(err error, msg string) { if err != nil { log.Fatalln(msg, err) } } func ResetDatabase() { Dbmap.TruncateTables() } func InitDb(dbname string) *modl.DbMap
{ db, err := sql.Open("sqlite3", "/tmp/"+dbname) CheckErr(err, "sql.Open failed") dbmap := modl.NewDbMap(db, modl.SqliteDialect{}) dbmap.AddTableWithName(Task{}, "tasks").SetKeys(true, "ID") dbmap.AddTableWithName(Project{}, "projects").SetKeys(true, "ID") Dbmap = dbmap err = dbmap.CreateTablesIfNotExists() CheckErr(err, "Create tables failed") return dbmap }
package main import ( "context" "fmt" "io" "io/ioutil" "os" "os/signal" "strings" "sync" "syscall" ) type threadSafePrintliner struct { l sync.Mutex w io.Writer } func (p *threadSafePrintliner) println(s string) { p.l.Lock() fmt.Fprintln(p.w, s) p.l.Unlock() } func readQuery(r io.Reader) string { s, _ := ioutil.ReadAll(r) return strings.TrimSpace(strings.Replace(string(s), "\n", " ", -1)) } func trimEmpty(s []string) []string { var r = make([]string, 0) for _, str := range s { if str != "" { r = append(r, str) } } return r } func awaitSignal(cancel context.CancelFunc) { signals := make(chan os.Signal) signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) <-signals cancel() } func newThreadSafePrintliner(w io.Writer) *threadSafePrintliner
{ return &threadSafePrintliner{w: w} }
package martini import ( "fmt" "log" "net/http" "runtime/debug" ) const ( panicHtml = `<html> <head><title>PANIC: %s</title></head> <style type="text/css"> html, body { font-family: "Roboto", sans-serif; color: #333333; background-color: #ea5343; margin: 0px; } h1 { color: #d04526; background-color: #ffffff; padding: 20px; border-bottom: 1px dashed #2b3848; } pre { margin: 20px; padding: 20px; border: 2px solid #2b3848; background-color: #ffffff; } </style> <body> <h1>PANIC</h1> <pre style="font-weight: bold;">%s</pre> <pre>%s</pre> </body> </html>` ) func Recovery() Handler
{ return func(res http.ResponseWriter, c Context, log *log.Logger) { defer func() { if err := recover(); err != nil { res.WriteHeader(http.StatusInternalServerError) log.Printf("PANIC: %s\n%s", err, debug.Stack()) if Env == Dev { res.Write([]byte(fmt.Sprintf(panicHtml, err, err, debug.Stack()))) } } }() c.Next() } }
package leetcode func minMoves(nums []int) int
{ sum, min := 0, (1<<31 - 1) for _, num := range nums { if min > num { min = num } sum += num } return sum - len(nums)*min }
package sidekick import ( "flag" "fmt" "log" "strings" ) type stringSlice []string func (ss stringSlice) String() string { return strings.Join(ss, ",") } func (ss *stringSlice) Set(s string) error { *ss = append(*ss, s); return nil } var ( Debug bool skips stringSlice cases stringSlice ) func init() { flag.Var(&skips, "skip", "skip test case") flag.Var(&cases, "case", "run test case") flag.BoolVar(&Debug, "debug", false, "enter debug mode") log.SetFlags(log.Lshortfile | log.LstdFlags) } func SkipCase(c interface{}) bool
{ for _, item := range skips { if item == fmt.Sprint(c) { return true } } for _, item := range cases { if item == fmt.Sprint(c) { return false } } if len(cases) > 0 { return true } return false }
package database import ( "github.com/oracle/oci-go-sdk/common" ) type PatchDetails struct { Action PatchDetailsActionEnum `mandatory:"false" json:"action,omitempty"` PatchId *string `mandatory:"false" json:"patchId"` } type PatchDetailsActionEnum string const ( PatchDetailsActionApply PatchDetailsActionEnum = "APPLY" PatchDetailsActionPrecheck PatchDetailsActionEnum = "PRECHECK" ) var mappingPatchDetailsAction = map[string]PatchDetailsActionEnum{ "APPLY": PatchDetailsActionApply, "PRECHECK": PatchDetailsActionPrecheck, } func GetPatchDetailsActionEnumValues() []PatchDetailsActionEnum { values := make([]PatchDetailsActionEnum, 0) for _, v := range mappingPatchDetailsAction { values = append(values, v) } return values } func (m PatchDetails) String() string
{ return common.PointerString(m) }
package swagger import ( "reflect" "strings" ) func (prop *ModelProperty) setDescription(field reflect.StructField) { if tag := field.Tag.Get("description"); tag != "" { prop.Description = tag } } func (prop *ModelProperty) setDefaultValue(field reflect.StructField) { if tag := field.Tag.Get("default"); tag != "" { prop.DefaultValue = Special(tag) } } func (prop *ModelProperty) setEnumValues(field reflect.StructField) { if tag := field.Tag.Get("enum"); tag != "" { prop.Enum = strings.Split(tag, "|") } } func (prop *ModelProperty) setMaximum(field reflect.StructField) { if tag := field.Tag.Get("maximum"); tag != "" { prop.Maximum = tag } } func (prop *ModelProperty) setMinimum(field reflect.StructField) { if tag := field.Tag.Get("minimum"); tag != "" { prop.Minimum = tag } } func (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) { prop.setDescription(field) prop.setEnumValues(field) prop.setMinimum(field) prop.setMaximum(field) prop.setUniqueItems(field) prop.setDefaultValue(field) } func (prop *ModelProperty) setUniqueItems(field reflect.StructField)
{ tag := field.Tag.Get("unique") switch tag { case "true": v := true prop.UniqueItems = &v case "false": v := false prop.UniqueItems = &v } }
package logging import ( "github.com/oracle/oci-go-sdk/v46/common" ) type ServiceSummary struct { TenantId *string `mandatory:"true" json:"tenantId"` ServicePrincipalName *string `mandatory:"true" json:"servicePrincipalName"` Endpoint *string `mandatory:"true" json:"endpoint"` Name *string `mandatory:"true" json:"name"` ResourceTypes []ResourceType `mandatory:"true" json:"resourceTypes"` Namespace *string `mandatory:"false" json:"namespace"` Id *string `mandatory:"false" json:"id"` } func (m ServiceSummary) String() string
{ return common.PointerString(m) }
package analyzer import ( . "github.com/levythu/gurgling" "time" "fmt" "strconv" ) type SimpleAnalyzer struct { } func ASimpleAnalyzer() Sandwich { return &SimpleAnalyzer{} } const token_returncode="SimpleAnalyzer-Status-Code" const token_starttime="SimpleAnalyzer-Start-Time" func logCode(res Response, c int) { res.F()[token_returncode]=c } func (this *SimpleAnalyzer)Final(req Request, res Response) { var timeStart, ok=res.F()[token_starttime].(int64) var timeElpase string if ok { var t=time.Now().UnixNano() timeElpase=strconv.FormatInt((t-timeStart)/1000000, 10)+"ms" } else { timeElpase="xxxx" } var statusCode, ok2=res.F()[token_returncode].(int) var codeStr string if ok2 { codeStr=strconv.Itoa(statusCode) } else { codeStr="---" } var url=req.R().URL fmt.Print("- "+timeElpase+"\t\t"+codeStr+"\t"+req.Method()+"\t"+url.Path) if url.RawQuery!="" { fmt.Println("?"+url.RawQuery) } else { fmt.Println("") } } func (this *SimpleAnalyzer)Handler(req Request, res Response) (bool, Request, Response)
{ var newRes=&logResponse { o: res, OnHeadSent: logCode, } newRes.F()[token_starttime]=time.Now().UnixNano() return true, req, newRes }
package database import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type GetAutonomousPatchRequest struct { AutonomousPatchId *string `mandatory:"true" contributesTo:"path" name:"autonomousPatchId"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` RequestMetadata common.RequestMetadata } func (request GetAutonomousPatchRequest) String() string { return common.PointerString(request) } func (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } func (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } type GetAutonomousPatchResponse struct { RawResponse *http.Response AutonomousPatch `presentIn:"body"` Etag *string `presentIn:"header" name:"etag"` OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response GetAutonomousPatchResponse) String() string { return common.PointerString(response) } func (response GetAutonomousPatchResponse) HTTPResponse() *http.Response { return response.RawResponse } func (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error)
{ return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) }
package comparisons import "jvmgo/ch05/instructions/base" import "jvmgo/ch05/rtda" type IF_ACMPEQ struct{ base.BranchInstruction } func (self *IF_ACMPEQ) Execute(frame *rtda.Frame) { if _acmp(frame) { base.Branch(frame, self.Offset) } } type IF_ACMPNE struct{ base.BranchInstruction } func (self *IF_ACMPNE) Execute(frame *rtda.Frame) { if !_acmp(frame) { base.Branch(frame, self.Offset) } } func _acmp(frame *rtda.Frame) bool
{ stack := frame.OperandStack() ref2 := stack.PopRef() ref1 := stack.PopRef() return ref1 == ref2 }
package cli import ( "fmt" "testing" ) func TestRequiredParameterNotSetError_Error(t *testing.T) { err := &RequiredParameterNotSetError{ Name: "name", } if err.Error() != "required parameter name not set" { t.Fail() } err = &RequiredParameterNotSetError{ Formatted: "formatted", } if err.Error() != "required parameter formatted not set" { t.Fail() } } func TestExitStatusError_Error(t *testing.T)
{ err := &ExitStatusError{ Code: 1, Err: fmt.Errorf("error"), } if err.Error() != "error" { t.Fatal() } }
package longestvalidparentheses func longestValidParentheses(s string) int
{ l := 0 if len(s) >= 1 { i, stack := 0, make([]int, len(s)+1) stack[0] = -1 for si := 0; si < len(s); si++ { if s[si] == '(' { i++ stack[i] = si } else { i-- if i < 0 { i = 0 stack[i] = si } else if tmp := si - stack[i]; tmp > l { l = tmp } } } } return l }
package util import "testing" func TestCharsLength(t *testing.T) { chars := ToChars([]byte("\tabc한글 ")) if chars.inBytes || chars.Length() != 8 || chars.TrimLength() != 5 { t.Error() } } func TestCharsToString(t *testing.T) { text := "\tabc한글 " chars := ToChars([]byte(text)) if chars.ToString() != text { t.Error() } } func TestTrimLength(t *testing.T) { check := func(str string, exp uint16) { chars := ToChars([]byte(str)) trimmed := chars.TrimLength() if trimmed != exp { t.Errorf("Invalid TrimLength result for '%s': %d (expected %d)", str, trimmed, exp) } } check("hello", 5) check("hello ", 5) check("hello ", 5) check(" hello", 5) check(" hello", 5) check(" hello ", 5) check(" hello ", 5) check("h o", 5) check(" h o ", 5) check(" ", 0) } func TestToCharsAscii(t *testing.T)
{ chars := ToChars([]byte("foobar")) if !chars.inBytes || chars.ToString() != "foobar" || !chars.inBytes { t.Error() } }
package testing import ( "time" "github.com/zinic/protobus/bus" "github.com/zinic/protobus/concurrent" ) func NewInjector(event bus.Event, interval time.Duration) (injector bus.Source) { return &InjectorSource { event: event, running: concurrent.NewReferenceLocker(false), interval: interval, } } type InjectorSource struct { event bus.Event running concurrent.ReferenceLocker interval time.Duration } func (injector *InjectorSource) Start(outgoing chan<- bus.Event, actx bus.ActorContext) (err error) { injector.running.Set(true) var elapsedNanos int64 = 0 for injector.running.Get().(bool) { then := time.Now() if elapsedNanos >= injector.interval.Nanoseconds() { elapsedNanos = 0 outgoing <- injector.event } time.Sleep(1 * time.Millisecond) elapsedNanos += time.Now().Sub(then).Nanoseconds() } return } func (injector *InjectorSource) Stop() (err error)
{ injector.running.Set(false) return }
package lru import ( "container/list" "sync" ) type kv struct { key interface{} value interface{} } type KVCache struct { mtx sync.Mutex cache map[interface{}]*list.Element list *list.List limit uint } func (m *KVCache) Lookup(key interface{}) (interface{}, bool) { var value interface{} m.mtx.Lock() node, exists := m.cache[key] if exists { m.list.MoveToFront(node) pair := node.Value.(*kv) value = pair.value } m.mtx.Unlock() return value, exists } func (m *KVCache) Contains(key interface{}) bool { m.mtx.Lock() node, exists := m.cache[key] if exists { m.list.MoveToFront(node) } m.mtx.Unlock() return exists } func (m *KVCache) Delete(key interface{}) { m.mtx.Lock() if node, exists := m.cache[key]; exists { m.list.Remove(node) delete(m.cache, key) } m.mtx.Unlock() } func NewKVCache(limit uint) KVCache { return KVCache{ cache: make(map[interface{}]*list.Element), list: list.New(), limit: limit, } } func (m *KVCache) Add(key interface{}, value interface{})
{ m.mtx.Lock() defer m.mtx.Unlock() if m.limit == 0 { return } if node, exists := m.cache[key]; exists { node.Value.(*kv).value = value m.list.MoveToFront(node) m.cache[key] = node return } if uint(len(m.cache))+1 > m.limit { node := m.list.Back() lru := node.Value.(*kv) delete(m.cache, lru.key) lru.key = key lru.value = value m.list.MoveToFront(node) m.cache[key] = node return } node := m.list.PushFront(&kv{key: key, value: value}) m.cache[key] = node }
package core import ( "k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common" "net/http" ) type GetVolumeKmsKeyRequest struct { VolumeId *string `mandatory:"true" contributesTo:"path" name:"volumeId"` IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` RequestMetadata common.RequestMetadata } func (request GetVolumeKmsKeyRequest) String() string { return common.PointerString(request) } func (request GetVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request) } func (request GetVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } func (request GetVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } type GetVolumeKmsKeyResponse struct { RawResponse *http.Response VolumeKmsKey `presentIn:"body"` Etag *string `presentIn:"header" name:"etag"` OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response { return response.RawResponse } func (response GetVolumeKmsKeyResponse) String() string
{ return common.PointerString(response) }
package matchers import ( "fmt" "strings" "github.com/cloudfoundry/cli/cf/terminal" "github.com/onsi/gomega" ) type SliceMatcher struct { expected [][]string failedAtIndex int } func ContainSubstrings(substrings ...[]string) gomega.OmegaMatcher { return &SliceMatcher{expected: substrings} } func (matcher *SliceMatcher) Match(actual interface{}) (success bool, err error) { actualStrings, ok := actual.([]string) if !ok { return false, nil } allStringsMatched := make([]bool, len(matcher.expected)) for index, expectedArray := range matcher.expected { for _, actualValue := range actualStrings { allStringsFound := true for _, expectedValue := range expectedArray { allStringsFound = allStringsFound && strings.Contains(terminal.Decolorize(actualValue), expectedValue) } if allStringsFound { allStringsMatched[index] = true break } } } for index, value := range allStringsMatched { if !value { matcher.failedAtIndex = index return false, nil } } return true, nil } func (matcher *SliceMatcher) NegatedFailureMessage(actual interface{}) string { actualStrings, ok := actual.([]string) if !ok { return fmt.Sprintf("Expected actual to be a slice of strings, but it's actually a %T", actual) } return fmt.Sprintf("expected to not find \"%s\" in actual:\n'%s'\n", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, "\n")) } func (matcher *SliceMatcher) FailureMessage(actual interface{}) string
{ actualStrings, ok := actual.([]string) if !ok { return fmt.Sprintf("Expected actual to be a slice of strings, but it's actually a %T", actual) } return fmt.Sprintf("expected to find \"%s\" in actual:\n'%s'\n", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, "\n")) }
package zebra import "fmt" const _AFI_name = "AFI_IPAFI_IP6AFI_ETHERAFI_MAX" var _AFI_index = [...]uint8{0, 6, 13, 22, 29} func (i AFI) String() string
{ i -= 1 if i >= AFI(len(_AFI_index)-1) { return fmt.Sprintf("AFI(%d)", i+1) } return _AFI_name[_AFI_index[i]:_AFI_index[i+1]] }
package iso20022 type ApplicationParameters4 struct { ApplicationIdentification *Max35Text `xml:"ApplId"` Version *Max256Text `xml:"Vrsn"` Parameters []*Max100KBinary `xml:"Params,omitempty"` EncryptedParameters *ContentInformationType10 `xml:"NcrptdParams,omitempty"` } func (a *ApplicationParameters4) SetApplicationIdentification(value string) { a.ApplicationIdentification = (*Max35Text)(&value) } func (a *ApplicationParameters4) SetVersion(value string) { a.Version = (*Max256Text)(&value) } func (a *ApplicationParameters4) AddParameters(value string) { a.Parameters = append(a.Parameters, (*Max100KBinary)(&value)) } func (a *ApplicationParameters4) AddEncryptedParameters() *ContentInformationType10
{ a.EncryptedParameters = new(ContentInformationType10) return a.EncryptedParameters }
package goschema type nullType struct { baseType } func NewNullType(description string) NullType { return &nullType{ baseType: baseType{ description: description, }, } } func (g *nullType) docString(field string, docPrefix string) string { return docString(field, g.description, docPrefix, "must be nothing (null)") } func (g *nullType) asJSONSchema() map[string]interface{}
{ data := map[string]interface{}{ "type": "null", } if g.description != "" { data["description"] = g.description } return data }
package suggest import ( "github.com/google/btree" "sync" ) type Suggester interface { Suggest(max int, q string) (result []string) } type Adder interface { Add(s string) } type Engine struct { incomingCh chan string awaitCh chan bool lock sync.RWMutex suggestions *btree.BTree } func NewEngine() *Engine { return newEngine() } func (e *Engine) Add(s string) { e.add(s) } func (e *Engine) Await() { e.await() } func NewSuggester(suggestions ...string) Suggester { return newSuggester(suggestions) } func (e *Engine) Suggest(max int, q string) (result []string)
{ return e.suggest(max, q) }
package controllers import ( "github.com/gin-gonic/gin" clayControllers "github.com/qb0C80aE/clay/controllers" "github.com/qb0C80aE/clay/extensions" "github.com/qb0C80aE/pottery/logics" "github.com/qb0C80aE/pottery/models" ) type hostGroupController struct { *clayControllers.BaseController } func newHostGroupController() extensions.Controller { controller := &hostGroupController{ BaseController: clayControllers.NewBaseController( models.SharedHostGroupModel(), logics.UniqueHostGroupLogic(), ), } return controller } func (controller *hostGroupController) RouteMap() map[int]map[int]gin.HandlerFunc { routeMap := map[int]map[int]gin.HandlerFunc{ extensions.MethodGet: { extensions.URLSingle: controller.GetSingle, extensions.URLMulti: controller.GetMulti, }, extensions.MethodPost: { extensions.URLMulti: controller.Create, }, extensions.MethodPut: { extensions.URLSingle: controller.Update, }, extensions.MethodDelete: { extensions.URLSingle: controller.Delete, }, } return routeMap } var uniqueHostGroupController = newHostGroupController() func init()
{ extensions.RegisterController(uniqueHostGroupController) }
package engine import "testing" func TestBackendLobbyMuxAddLobby(t *testing.T) { mux := NewBackendLobbyMux() mux.AddLobby("/foo", &backendLobby{}) if _, ok := mux.m["/foo"]; !ok { t.Errorf("Expected to add lobby") } } func TestBackendLobbyMuxDeleteLobby(t *testing.T) { mux := NewBackendLobbyMux() l := &backendLobby{queue: make(chan interface{})} mux.AddLobby("/foo", l) if ok := mux.DeleteLobby("/foo"); !ok { t.Errorf("Expected to delete lobby") } if l.IsAlive() { t.Errorf("Lobby should be killed when deleting from the mux") } if _, ok := mux.m["/foo"]; ok { t.Errorf("Expected to delete lobby") } if ok := mux.DeleteLobby("/bar"); ok { t.Errorf("Expected to not delete non existing lobby") } } func TestBackendLobbyMuxMatch(t *testing.T)
{ mux := NewBackendLobbyMux() mux.AddLobby("/foo", &backendLobby{}) if lobby := mux.Match("/foo"); lobby == nil { t.Errorf("Expected to match existing lobby") } if lobby := mux.Match("/bar"); lobby != nil { t.Errorf("Expected to not match non existing lobby") } }
package helper import ( "encoding/base64" "strings" "time" "github.com/insionng/yougam/libraries/flosch/pongo2.v3" ) func ConvertToBase64(in string) string { return base64.StdEncoding.EncodeToString([]byte(in)) } func ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value { return pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String()))) } func SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value { return pongo2.AsValue(Split(in.String(), splitor.String())) } func MarkdownByPongo2(in *pongo2.Value) *pongo2.Value { return pongo2.AsValue(Markdown(in.String())) } func CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value { return pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String())) } func Cropword(in string, start int, length int, symbol string) string { return Substr(in, start, length, symbol) } func File(s string) string { if len(s) > 0 { if strings.HasPrefix(s, "http") || strings.HasPrefix(s, "/identicon") { return s } else { return "/file" + s } } return s } func Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value
{ return pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String())) }
package example import ( "testing" "github.com/remogatto/prettytest" "launchpad.net/gocheck" ) type testSuite struct { prettytest.Suite } func TestRunner(t *testing.T) { prettytest.Run( t, new(testSuite), ) } func (t *testSuite) TestTrueIsTrue() { t.True(true) } func (t *testSuite) TestNot() { t.Not(t.Path("foo")) } func (t *testSuite) TestGoCheck() { t.Check("foo", gocheck.Equals, "foo") } func (t *testSuite) TestMustFail() { t.Error("This test must fail.") t.MustFail() } func (t *testSuite) TestInequality() { t.Equal("awesome", "ugly") t.MustFail() } func (t *testSuite) TestEquality()
{ t.Equal("awesome", "awesome") }
package ast import ( "fmt" "github.com/kedebug/LispEx/binder" "github.com/kedebug/LispEx/constants" "github.com/kedebug/LispEx/scope" . "github.com/kedebug/LispEx/value" ) type Set struct { Pattern *Name Value Node } func (self *Set) Eval(env *scope.Scope) Value { val := self.Value.Eval(env) binder.Assign(env, self.Pattern.Identifier, val) return nil } func (self *Set) String() string { return fmt.Sprintf("(%s %s %s)", constants.SET, self.Pattern, self.Value) } func NewSet(pattern *Name, val Node) *Set
{ return &Set{Pattern: pattern, Value: val} }
package router import ( "sync/atomic" "github.com/AsynkronIT/protoactor-go/actor" ) type roundRobinGroupRouter struct { GroupRouter } type roundRobinPoolRouter struct { PoolRouter } type roundRobinState struct { index int32 routees *actor.PIDSet values []actor.PID } func (state *roundRobinState) SetRoutees(routees *actor.PIDSet) { state.routees = routees state.values = routees.Values() } func (state *roundRobinState) GetRoutees() *actor.PIDSet { return state.routees } func (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) { pid := roundRobinRoutee(&state.index, state.values) pid.Request(message, sender) } func NewRoundRobinPool(size int) *actor.Props { return actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}})) } func NewRoundRobinGroup(routees ...*actor.PID) *actor.Props { return actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}})) } func (config *roundRobinGroupRouter) CreateRouterState() Interface { return &roundRobinState{} } func roundRobinRoutee(index *int32, routees []actor.PID) actor.PID { i := int(atomic.AddInt32(index, 1)) if i < 0 { *index = 0 i = 0 } mod := len(routees) routee := routees[i%mod] return routee } func (config *roundRobinPoolRouter) CreateRouterState() Interface
{ return &roundRobinState{} }
package daemon import ( "testing" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/runconfig" ) func TestValidContainerNames(t *testing.T) { invalidNames := []string{"-rm", "&sdfsfd", "safd%sd"} validNames := []string{"word-word", "word_word", "1weoid"} for _, name := range invalidNames { if validContainerNamePattern.MatchString(name) { t.Fatalf("%q is not a valid container name and was returned as valid.", name) } } for _, name := range validNames { if !validContainerNamePattern.MatchString(name) { t.Fatalf("%q is a valid container name and was returned as invalid.", name) } } } func TestContainerStopSignal(t *testing.T) { c := &Container{ CommonContainer: CommonContainer{ Config: &runconfig.Config{}, }, } def, err := signal.ParseSignal(signal.DefaultStopSignal) if err != nil { t.Fatal(err) } s := c.stopSignal() if s != int(def) { t.Fatalf("Expected %v, got %v", def, s) } c = &Container{ CommonContainer: CommonContainer{ Config: &runconfig.Config{StopSignal: "SIGKILL"}, }, } s = c.stopSignal() if s != 9 { t.Fatalf("Expected 9, got %v", s) } } func TestGetFullName(t *testing.T)
{ name, err := GetFullContainerName("testing") if err != nil { t.Fatal(err) } if name != "/testing" { t.Fatalf("Expected /testing got %s", name) } if _, err := GetFullContainerName(""); err == nil { t.Fatal("Error should not be nil") } }
package service import ( "fmt" "github.com/mrcsparker/ifin/api" "github.com/mrcsparker/ifin/model" "log" ) type Counters struct { } func (self Counters) UpdateCounter(id string) model.CounterEntity { s := api.Setup() res := model.CounterEntity{} url := "http://localhost:8080/nifi-api/counters/{id}" resp, err := s.Put(url, nil, &res, nil) if err != nil { log.Fatal(err) } if resp.Status() != 200 { fmt.Println(res) } return res } func (self Counters) GetCounters(nodewise bool, clusterNodeId string) model.CountersEntity
{ s := api.Setup() res := model.CountersEntity{} url := "http://localhost:8080/nifi-api/counters" resp, err := s.Get(url, nil, &res, nil) if err != nil { log.Fatal(err) } if resp.Status() != 200 { fmt.Println(res) } return res }
package gogen import ( "bytes" "io/ioutil" "text/template" "github.com/gobuffalo/genny" "github.com/pkg/errors" ) var TemplateHelpers = map[string]interface{}{} func renderWithTemplate(f genny.File, data interface{}, helpers template.FuncMap) (genny.File, error) { if f == nil { return f, errors.New("file was nil") } path := f.Name() t := template.New(path) if helpers != nil { t = t.Funcs(helpers) } b, err := ioutil.ReadAll(f) if err != nil { return f, errors.WithStack(err) } t, err = t.Parse(string(b)) if err != nil { return f, errors.WithStack(err) } var bb bytes.Buffer if err = t.Execute(&bb, data); err != nil { err = errors.WithStack(err) return f, errors.WithStack(err) } return genny.StripExt(genny.NewFile(path, &bb), ".tmpl"), nil } func TemplateTransformer(data interface{}, helpers map[string]interface{}) genny.Transformer
{ if helpers == nil { helpers = TemplateHelpers } t := genny.NewTransformer(".tmpl", func(f genny.File) (genny.File, error) { return renderWithTemplate(f, data, helpers) }) t.StripExt = true return t }
package crypto import ( "crypto/hmac" "crypto/sha512" "encoding/base64" "encoding/hex" ) func HS512Base64(in, secret string) string { key := []byte(secret) h := hmac.New(sha512.New, key) h.Write([]byte(in)) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } func HS512Hex(in, secret string) string { key := []byte(secret) h := hmac.New(sha512.New, key) h.Write([]byte(in)) return hex.EncodeToString(h.Sum(nil)) } func CompareHS512Hex(in, secret, hs512Hex string) bool { if HS512Hex(in, secret) == hs512Hex { return true } return false } func HS512Byte(in, secret []byte) []byte
{ h := hmac.New(sha512.New, secret) h.Write(in) return h.Sum(nil) }
package donna func (gen *MoveGen) generateCaptures() *MoveGen { color := gen.p.color return gen.pawnCaptures(color).pieceCaptures(color) } func (gen *MoveGen) pawnCaptures(color int) *MoveGen { enemy := gen.p.outposts[color^1] for pawns := gen.p.outposts[pawn(color)]; pawns.any(); pawns = pawns.pop() { square := pawns.first() if rank(color, square) != A7H7 { gen.movePawn(square, gen.p.targets(square) & enemy) } else { for bm := gen.p.targets(square); bm.any(); bm = bm.pop() { target := bm.first() mQ, _, _, _ := NewPromotion(gen.p, square, target) gen.add(mQ) } } } return gen } func (gen *MoveGen) pieceCaptures(color int) *MoveGen
{ enemy := gen.p.outposts[color^1] for bm := gen.p.outposts[color] ^ gen.p.outposts[pawn(color)] ^ gen.p.outposts[king(color)]; bm.any(); bm = bm.pop() { square := bm.first() gen.movePiece(square, gen.p.targets(square) & enemy) } if gen.p.outposts[king(color)].any() { square := gen.p.king[color] gen.moveKing(square, gen.p.targets(square) & enemy) } return gen }
package types import ( "bytes" "encoding/gob" "time" ) type CommitObject struct { Author string Message string Time time.Time Tree Hash Parents []Hash } func (commit *CommitObject) Serialize() []byte { buffer := new(bytes.Buffer) e := gob.NewEncoder(buffer) err := e.Encode(commit) if err != nil { panic(err) } return buffer.Bytes() } func DeserializeCommitObject(input []byte) *CommitObject
{ buffer := bytes.NewBuffer(input) dec := gob.NewDecoder(buffer) var commit CommitObject err := dec.Decode(&commit) if err != nil { panic(err) } return &commit }
package client import ( "context" "math" "time" ) type BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error) func exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error)
{ if attempts == 0 { return time.Duration(0), nil } return time.Duration(math.Pow(10, float64(attempts))) * time.Millisecond, nil }
package head import ( "net/http" "github.com/arapov/pile/lib/flight" "github.com/blue-jay/core/router" ) var ( uri = "/roster" ) func Load() { router.Get(uri+"/head", IndexHead) router.Get(uri+"/all", IndexAll) } func IndexHead(w http.ResponseWriter, r *http.Request) { c := flight.Context(w, r) v := c.View.New("head/index") v.Vars["name"] = "TC-UA-Steward" v.Vars["suffix"] = "heads" v.Render(w, r) } func IndexAll(w http.ResponseWriter, r *http.Request)
{ c := flight.Context(w, r) v := c.View.New("head/index") v.Vars["name"] = "Everyone in organization" v.Vars["suffix"] = "all" v.Render(w, r) }
package http import ( "net" "time" ) type TimeoutConn struct { QuirkConn readTimeout time.Duration writeTimeout time.Duration } func (c *TimeoutConn) setReadTimeout() { if c.readTimeout != 0 && c.canSetReadDeadline() { c.SetReadDeadline(time.Now().UTC().Add(c.readTimeout)) } } func (c *TimeoutConn) setWriteTimeout() { if c.writeTimeout != 0 { c.SetWriteDeadline(time.Now().UTC().Add(c.writeTimeout)) } } func (c *TimeoutConn) Write(b []byte) (n int, err error) { c.setWriteTimeout() return c.Conn.Write(b) } func NewTimeoutConn(c net.Conn, readTimeout, writeTimeout time.Duration) *TimeoutConn { return &TimeoutConn{ QuirkConn: QuirkConn{Conn: c}, readTimeout: readTimeout, writeTimeout: writeTimeout, } } func (c *TimeoutConn) Read(b []byte) (n int, err error)
{ c.setReadTimeout() return c.Conn.Read(b) }
package core import ( "k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common" "net/http" ) type RemoveNetworkSecurityGroupSecurityRulesRequest struct { NetworkSecurityGroupId *string `mandatory:"true" contributesTo:"path" name:"networkSecurityGroupId"` RemoveNetworkSecurityGroupSecurityRulesDetails `contributesTo:"body"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` RequestMetadata common.RequestMetadata } func (request RemoveNetworkSecurityGroupSecurityRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request) } func (request RemoveNetworkSecurityGroupSecurityRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } func (request RemoveNetworkSecurityGroupSecurityRulesRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } type RemoveNetworkSecurityGroupSecurityRulesResponse struct { RawResponse *http.Response OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response RemoveNetworkSecurityGroupSecurityRulesResponse) String() string { return common.PointerString(response) } func (response RemoveNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response { return response.RawResponse } func (request RemoveNetworkSecurityGroupSecurityRulesRequest) String() string
{ return common.PointerString(request) }
package middleware import ( "github.com/drone/drone/version" "github.com/gin-gonic/gin" ) func Version(c *gin.Context)
{ c.Header("X-DRONE-VERSION", version.Version) }
package clipboard import ( "time" ) type Duration struct { time.Duration } func (d *Duration) UnmarshalText(text []byte) error { var err error d.Duration, err = time.ParseDuration(string(text)) return err } func (d Duration) MarshalText() ([]byte, error)
{ return []byte(d.String()), nil }
package gnr import ( "math" ) type FalloffFunc func(ir *InteractionResult) *InteractionResult type FlatShader struct { Object FalloffFunc } func NewLinearFalloffFunc(lightDir *Vector3f) FalloffFunc { return func(ir *InteractionResult) *InteractionResult { cosAngle := VectorProduct(lightDir, ir.Normal) / lightDir.Magnitude() / ir.Normal.Magnitude() angle := math.Acos(cosAngle) ir.Color = VLerpCap(0, math.Pi, ColorBlack, ir.Color)(angle) return ir } } func (fs *FlatShader) RayInteraction(r *Ray) []*InteractionResult
{ irs := fs.Object.RayInteraction(r) irs = InteractionResultSlice(irs).SelectInteractionResult(fs.FalloffFunc) return irs }
package blockchain import ( "github.com/cfromknecht/certcoin/crypto" db "github.com/syndtr/goleveldb/leveldb" "log" ) type SVP struct { HeaderDBPath string LastHeader BlockHeader } func (s *SVP) ValidHeader(header BlockHeader) bool { if header.SeqNum == 0 { return header.PrevHash == crypto.SHA256Sum{} && header.ValidPoW() } return s.LastHeader.Hash() == header.PrevHash && header.ValidPoW() } func (s *SVP) WriteHeader(header BlockHeader) error { headerDB, err := db.OpenFile(s.HeaderDBPath, nil) if err != nil { log.Println(err) panic("Unable to open header database") } defer headerDB.Close() headerJson := header.Json() hash := header.Hash() err = headerDB.Put(hash[:], headerJson, nil) if err != nil { log.Println(err) return err } log.Println("Last header:", header) s.LastHeader = header return nil } func NewSVP() SVP
{ svp := SVP{ HeaderDBPath: "db/header.db", } err := svp.WriteHeader(GenesisBlock().Header) if err != nil { log.Println(err) panic("Unable to add genesis block header to database") } return svp }
package geoMath import ( "github.com/helmutkemper/mgo/bson" "github.com/helmutkemper/db" ) type RelationErrorStt struct { IdMongo bson.ObjectId `bson:"_id,omitempty"` IdParser bson.ObjectId `bson:"IdParser,omitempty"` Id int64 IdSearched int64 DbCollectionName string `bson:"dbCollectionName" json:"-"` *db.DbStt `bson:"-"` } func ( RelationErrorAStt *RelationErrorStt ) SetDbCollectionName( nameAStr string ){ RelationErrorAStt.DbCollectionName = nameAStr } func ( RelationErrorAStt *RelationErrorStt ) FindOne( queryAObj bson.M ) error { err := RelationErrorAStt.DbStt.TestConnection() if err != nil { return err } return RelationErrorAStt.DbStt.FindOne( RelationErrorAStt.DbCollectionName, &RelationErrorAStt, queryAObj ) } func ( RelationErrorAStt *RelationErrorStt ) RemoveAll( queryAObj bson.M ) error { err := RelationErrorAStt.DbStt.TestConnection() if err != nil { return err } _, ret := RelationErrorAStt.DbStt.RemoveAll( RelationErrorAStt.DbCollectionName, queryAObj ) return ret } func ( RelationErrorAStt *RelationErrorStt ) Insert() error
{ var err error err = RelationErrorAStt.DbStt.TestConnection() if err != nil{ return err } RelationErrorAStt.IdMongo, err = RelationErrorAStt.DbStt.GetMongoId() if err != nil{ return err } if RelationErrorAStt.DbStt.HasIndex( RelationErrorAStt.DbCollectionName, "id" ) != true { RelationErrorAStt.DbStt.IndexKeyMake ( RelationErrorAStt.DbCollectionName, "id" ) } if RelationErrorAStt.DbStt.HasIndex( RelationErrorAStt.DbCollectionName, "idSearched" ) != true { RelationErrorAStt.DbStt.IndexKeyMake ( RelationErrorAStt.DbCollectionName, "idSearched" ) } return RelationErrorAStt.DbStt.Insert( RelationErrorAStt.DbCollectionName, RelationErrorAStt ) }
package models import ( ciliumModels "github.com/cilium/cilium/api/v1/models" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) type HealthResponse struct { Cilium ciliumModels.StatusResponse `json:"cilium,omitempty"` SystemLoad *LoadResponse `json:"system-load,omitempty"` Uptime string `json:"uptime,omitempty"` } func (m *HealthResponse) Validate(formats strfmt.Registry) error { var res []error if err := m.validateSystemLoad(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *HealthResponse) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } func (m *HealthResponse) UnmarshalBinary(b []byte) error { var res HealthResponse if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } func (m *HealthResponse) validateSystemLoad(formats strfmt.Registry) error
{ if swag.IsZero(m.SystemLoad) { return nil } if m.SystemLoad != nil { if err := m.SystemLoad.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("system-load") } return err } } return nil }
package kernel import ( "fmt" "os/exec" "strings" ) func getRelease(osName string) (string, error) { var release string data := strings.Split(osName, "\n") for _, line := range data { if !strings.Contains(line, "Kernel Version") { continue } content := strings.SplitN(line, ":", 2) if len(content) != 2 { return "", fmt.Errorf("Kernel Version is invalid") } prettyNames := strings.SplitN(strings.TrimSpace(content[1]), " ", 2) if len(prettyNames) != 2 { return "", fmt.Errorf("Kernel Version needs to be 'Darwin x.x.x' ") } release = prettyNames[1] } return release, nil } func getSPSoftwareDataType() (string, error) { cmd := exec.Command("system_profiler", "SPSoftwareDataType") osName, err := cmd.Output() if err != nil { return "", err } return string(osName), nil } func GetKernelVersion() (*VersionInfo, error)
{ osName, err := getSPSoftwareDataType() if err != nil { return nil, err } release, err := getRelease(osName) if err != nil { return nil, err } return ParseRelease(release) }
package block import ( "github.com/juju/cmd/v3" "github.com/juju/juju/jujuclient" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/cmd/modelcmd" ) func NewEnableCommandForTest(store jujuclient.ClientStore, api unblockClientAPI, err error) cmd.Command { cmd := &enableCommand{ apiFunc: func(_ newAPIRoot) (unblockClientAPI, error) { return api, err }, } cmd.SetClientStore(store) return modelcmd.Wrap(cmd) } type listMockAPI interface { blockListAPI ListBlockedModels() ([]params.ModelBlockInfo, error) } func NewListCommandForTest(store jujuclient.ClientStore, api listMockAPI, err error) cmd.Command { cmd := &listCommand{ apiFunc: func(_ newAPIRoot) (blockListAPI, error) { return api, err }, controllerAPIFunc: func(_ newControllerAPIRoot) (controllerListAPI, error) { return api, err }, } cmd.SetClientStore(store) return modelcmd.Wrap(cmd) } func NewDisableCommandForTest(store jujuclient.ClientStore, api blockClientAPI, err error) cmd.Command
{ cmd := &disableCommand{ apiFunc: func(_ newAPIRoot) (blockClientAPI, error) { return api, err }, } cmd.SetClientStore(store) return modelcmd.Wrap(cmd) }
package main import "fmt" func main() { const freezingF, boilingF = 32.0, 212.0 fmt.Printf("%g°F = %g°C\n", freezingF, fToC(freezingF)) fmt.Printf("%g°F = %g°C\n", boilingF, fToC(boilingF)) } func fToC(f float64) float64
{ return (f - 32) * 5 / 9 }
package box import ( "golang.org/x/crypto/curve25519" "golang.org/x/crypto/nacl/secretbox" "golang.org/x/crypto/salsa20/salsa" "io" ) const Overhead = secretbox.Overhead func GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) { publicKey = new([32]byte) privateKey = new([32]byte) _, err = io.ReadFull(rand, privateKey[:]) if err != nil { publicKey = nil privateKey = nil return } curve25519.ScalarBaseMult(publicKey, privateKey) return } var zeros [16]byte func Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) { curve25519.ScalarMult(sharedKey, privateKey, peersPublicKey) salsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma) } func Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte { var sharedKey [32]byte Precompute(&sharedKey, peersPublicKey, privateKey) return secretbox.Seal(out, message, nonce, &sharedKey) } func SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte { return secretbox.Seal(out, message, nonce, sharedKey) } func OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) { return secretbox.Open(out, box, nonce, sharedKey) } func Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool)
{ var sharedKey [32]byte Precompute(&sharedKey, peersPublicKey, privateKey) return secretbox.Open(out, box, nonce, &sharedKey) }
package main import ( "fmt" "github.com/polariseye/polarserver/common" "github.com/polariseye/polarserver/common/errorCode" "github.com/polariseye/polarserver/moduleManage" ) type testStruct struct { className string } var TestBLL *testStruct func init() { TestBLL = NewTestStruct() moduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) { return NewTestStruct(), moduleManage.NormalModule }) } func (this *testStruct) InitModule() []error { fmt.Println("初始化") return nil } func (this *testStruct) CheckModule() []error { fmt.Println("check") return nil } func (this *testStruct) ConvertModule() []error { fmt.Println("数据转换") return nil } func (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel { result := common.NewResultModel(errorCode.ClientDataError) result.Value["Hello"] = name + "_" + this.Name() result.Value["Extra"] = d result.SetNormalError(errorCode.Success) return result } func NewTestStruct() *testStruct { return &testStruct{ className: "TestBLL", } } func (this *testStruct) Name() string
{ return this.className }
package crypto import ( "bytes" "io/ioutil" . "github.com/tendermint/go-common" "golang.org/x/crypto/openpgp/armor" ) func EncodeArmor(blockType string, headers map[string]string, data []byte) string { buf := new(bytes.Buffer) w, err := armor.Encode(buf, blockType, headers) if err != nil { PanicSanity("Error encoding ascii armor: " + err.Error()) } _, err = w.Write(data) if err != nil { PanicSanity("Error encoding ascii armor: " + err.Error()) } err = w.Close() if err != nil { PanicSanity("Error encoding ascii armor: " + err.Error()) } return string(buf.Bytes()) } func DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error)
{ buf := bytes.NewBufferString(armorStr) block, err := armor.Decode(buf) if err != nil { return "", nil, nil, err } data, err = ioutil.ReadAll(block.Body) if err != nil { return "", nil, nil, err } return block.Type, block.Header, data, nil }
package extra import ( "github.com/json-iterator/go" "strings" "unicode" ) func SetNamingStrategy(translate func(string) string) { jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate}) } type namingStrategyExtension struct { jsoniter.DummyExtension translate func(string) string } func LowerCaseWithUnderscores(name string) string { newName := []rune{} for i, c := range name { if i == 0 { newName = append(newName, unicode.ToLower(c)) } else { if unicode.IsUpper(c) { newName = append(newName, '_') newName = append(newName, unicode.ToLower(c)) } else { newName = append(newName, c) } } } return string(newName) } func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor)
{ for _, binding := range structDescriptor.Fields { if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{ continue } tag, hastag := binding.Field.Tag().Lookup("json") if hastag { tagParts := strings.Split(tag, ",") if tagParts[0] == "-" { continue } if tagParts[0] != "" { continue } } binding.ToNames = []string{extension.translate(binding.Field.Name())} binding.FromNames = []string{extension.translate(binding.Field.Name())} } }
package main import ( "encoding/json" "fmt" "log" "net/http" "strings" ) func main() { http.HandleFunc("/", mainHandle) if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal("Listen and serve:", err) } } type reply struct { Language string `json:"language"` Os string `json:"software"` IP string `json:"ipaddress"` } func mainHandle(w http.ResponseWriter, r *http.Request) { header := r.Header h := fmt.Sprintf("%v", header) addr := r.RemoteAddr os := parseOs(h) l := parseLang(h) ip := parseIP(addr) reply := reply{Language: l, Os: os, IP: ip} out, err := json.MarshalIndent(reply, "", " ") if err != nil { fmt.Println("Cannot produce json", err) return } fmt.Fprintf(w, "%s\n", out) } func parseIP(addr string) string { ip := strings.Split(addr, ":")[0] return ip } func parseOs(h string) string { tag := strings.Index(h, "User-Agent") start := strings.Index(h[tag:], "(") start += tag + 1 end := strings.Index(h[start:], ")") end += start return h[start:end] } func parseLang(h string) string
{ tag := strings.Index(h, "Accept-Language:") start := strings.Index(h[tag:], "[") start += tag + 1 end := strings.Index(h[start:], "]") end += start l := h[start:end] return strings.Split(l, ";")[0] }
package sqlite import ( "testing" "github.com/anmil/quicknote/test" ) var tableNames = []string{ "books", "note_book_tag", "note_tag", "notes", "sqlite_sequence", "tags", } func openDatabase(t *testing.T) *Database { db, err := NewDatabase("file::memory:?cache=shared") if err != nil { t.Fatal(err) } return db } func TestCreateDatabaseSQLite(t *testing.T) { db := openDatabase(t) defer closeDatabase(db, t) if tables, err := db.GetTableNames(); err != nil { t.Fatal(err) } else if !test.StringSliceEq(tables, tableNames) { t.Fatal("Database either has extra or is missing tables") } } func closeDatabase(db *Database, t *testing.T)
{ if err := db.Close(); err != nil { t.Error(err) } }
package ig import "fmt" func (ic *IntelliClimate) SetTempTarget(target float64) error { return fmt.Errorf("not implemented") } func (ic *IntelliClimate) SetRHTarget(target float64) error { return fmt.Errorf("not implemented") } func (ic *IntelliClimate) EnableCO2Dosing() error { return fmt.Errorf("not implemented") } func (ic *IntelliClimate) DisableCO2Dosing() error { return fmt.Errorf("not implemented") } func (ic *IntelliClimate) SetCO2Target(target float64) error
{ return fmt.Errorf("not implemented") }
package gospec import ( "fmt" filepath "path" "runtime" ) type Location struct { name string file string line int } func currentLocation() *Location { return newLocation(1) } func callerLocation() *Location { return newLocation(2) } func newLocation(n int) *Location { if pc, _, _, ok := runtime.Caller(n + 1); ok { return locationForPC(pc) } return nil } func locationForPC(pc uintptr) *Location { pc = pcOfWhereCallWasMade(pc) f := runtime.FuncForPC(pc) name := f.Name() file, line := f.FileLine(pc) return &Location{name, file, line} } func pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr { return pcOfWhereCallReturnsTo - 1 } func (this *Location) File() string { return this.file } func (this *Location) FileName() string { return filename(this.file) } func (this *Location) Line() int { return this.line } func filename(path string) string { _, file := filepath.Split(path) return file } func (this *Location) equals(that *Location) bool { return this.name == that.name && this.file == that.file && this.line == that.line } func (this *Location) String() string { return fmt.Sprintf("%v:%v", this.FileName(), this.Line()) } func (this *Location) Name() string
{ return this.name }
package udp import ( "reflect" "time" "shadowss/pkg/config" "shadowss/pkg/crypto" "github.com/golang/glog" ) type UDPServer struct { Config *config.ConnectionInfo udpProxy *Proxy } func NewUDPServer(cfg *config.ConnectionInfo) *UDPServer { return &UDPServer{ Config: cfg, } } func (udpSrv *UDPServer) Stop() { glog.V(5).Infof("udp server close %v\r\n", udpSrv.Config) udpSrv.udpProxy.Stop() } func (udpSrv *UDPServer) Traffic() (int64, int64) { return udpSrv.udpProxy.Traffic() } func (udpSrv *UDPServer) Compare(client *config.ConnectionInfo) bool { return reflect.DeepEqual(udpSrv.Config, client) } func (udpSrv *UDPServer) GetListenPort() int { return udpSrv.Config.Port } func (udpSrv *UDPServer) GetConfig() config.ConnectionInfo { return *udpSrv.Config } func (udpSrv *UDPServer) GetLastActiveTime() time.Time { return time.Now() } func (udpSrv *UDPServer) Run()
{ password := udpSrv.Config.Password method := udpSrv.Config.EncryptMethod port := udpSrv.Config.Port auth := udpSrv.Config.EnableOTA timeout := time.Duration(udpSrv.Config.Timeout) * time.Second crypto, err := crypto.NewCrypto(method, password) if err != nil { glog.Errorf("Error generating cipher for udp port: %d %v\n", port, err) return } proxy := NewProxy(port, crypto, auth, timeout) if proxy == nil { glog.Errorf("listening upd port: %v error:%v\r\n", port, err) return } udpSrv.udpProxy = proxy udpSrv.Config.Port = udpSrv.udpProxy.GetPort() go proxy.RunProxy() }
package entities const ( ActionMove = iota + 1 ActionAttack ActionCastSpell ActionGather ActionLoot ActionConsume ) type Action interface { SetTarget(Entity) SetSelf(Entity) GetTypeAction() uint8 GetSelf() Entity GetTarget() Entity Play() error } type SimpleAction struct { self Entity target Entity typeAction uint8 } func (action *SimpleAction) GetTypeAction() uint8 { return action.GetTypeAction() } func (action *SimpleAction) GetTarget() Entity { return action.target } func (action *SimpleAction) SetSelf(self Entity) { action.self = self } func (action *SimpleAction) GetSelf() Entity { return action.self } func (action *SimpleAction) Play() error { return nil } func (action *SimpleAction) SetTarget(target Entity)
{ action.target = target }
package gooh type MemoryContext struct { data map[string]interface{} } func (c *MemoryContext) Get(k string) (interface{}, error) { return c.data[k], nil } func (c *MemoryContext) Exists(k string) (bool, error) { _, ok := c.data[k] return ok, nil } func (c *MemoryContext) Set(k string, d interface{}) error
{ if c.data == nil { c.data = make(map[string]interface{}) } c.data[k] = d return nil }
package iso20022 type CardPaymentTransaction42 struct { SaleReferenceIdentification *Max35Text `xml:"SaleRefId,omitempty"` TransactionIdentification *TransactionIdentifier1 `xml:"TxId"` RecipientTransactionIdentification *Max35Text `xml:"RcptTxId,omitempty"` ReconciliationIdentification *Max35Text `xml:"RcncltnId,omitempty"` InterchangeData *Max140Text `xml:"IntrchngData,omitempty"` TransactionDetails *CardPaymentTransactionDetails22 `xml:"TxDtls"` } func (c *CardPaymentTransaction42) AddTransactionIdentification() *TransactionIdentifier1 { c.TransactionIdentification = new(TransactionIdentifier1) return c.TransactionIdentification } func (c *CardPaymentTransaction42) SetRecipientTransactionIdentification(value string) { c.RecipientTransactionIdentification = (*Max35Text)(&value) } func (c *CardPaymentTransaction42) SetReconciliationIdentification(value string) { c.ReconciliationIdentification = (*Max35Text)(&value) } func (c *CardPaymentTransaction42) SetInterchangeData(value string) { c.InterchangeData = (*Max140Text)(&value) } func (c *CardPaymentTransaction42) AddTransactionDetails() *CardPaymentTransactionDetails22 { c.TransactionDetails = new(CardPaymentTransactionDetails22) return c.TransactionDetails } func (c *CardPaymentTransaction42) SetSaleReferenceIdentification(value string)
{ c.SaleReferenceIdentification = (*Max35Text)(&value) }
package cleanhttp import ( "net" "net/http" "runtime" "time" ) func DefaultTransport() *http.Transport { transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } SetTransportFinalizer(transport) return transport } func DefaultClient() *http.Client { return &http.Client{ Transport: DefaultTransport(), } } func SetTransportFinalizer(transport *http.Transport)
{ runtime.SetFinalizer(&transport, func(t **http.Transport) { (*t).CloseIdleConnections() }) }
package calendar import ( "time" ) var ( entries = make(map[int]Entry) index int ) type Entry struct { ID int Title string Starts time.Time Finishes time.Time } func (e Entry) Duration() time.Duration { return e.Finishes.Sub(e.Starts) } func Lookup(id int) (Entry, bool) { e, isPresent := entries[id] return e, isPresent } func Add(e Entry) Entry { index++ e.ID = index Update(e) return e } func Remove(id int) { delete(entries, id) } func Count() int { return len(entries) } func All() []Entry { all := []Entry{} for _, e := range entries { all = append(all, e) } return all } func Update(e Entry)
{ entries[e.ID] = e }
package conversion import ( "encoding/json" "errors" "fmt" ) func (s *Scheme) Decode(data []byte) (interface{}, error) { version, kind, err := s.DataVersionAndKind(data) if err != nil { return nil, err } if version == "" && s.InternalVersion != "" { return nil, fmt.Errorf("version not set in '%s'", string(data)) } if kind == "" { return nil, fmt.Errorf("kind not set in '%s'", string(data)) } obj, err := s.NewObject(version, kind) if err != nil { return nil, err } if err := json.Unmarshal(data, obj); err != nil { return nil, err } if err := s.SetVersionAndKind("", "", obj); err != nil { return nil, err } if s.InternalVersion != version { objOut, err := s.NewObject(s.InternalVersion, kind) if err != nil { return nil, err } if err := s.converter.Convert(obj, objOut, 0, s.generateConvertMeta(version, s.InternalVersion)); err != nil { return nil, err } obj = objOut } return obj, nil } func (s *Scheme) DecodeInto(data []byte, obj interface{}) error
{ if len(data) == 0 { return errors.New("empty input") } dataVersion, dataKind, err := s.DataVersionAndKind(data) if err != nil { return err } objVersion, objKind, err := s.ObjectVersionAndKind(obj) if err != nil { return err } if dataKind == "" { dataKind = objKind } if dataVersion == "" { dataVersion = objVersion } external, err := s.NewObject(dataVersion, dataKind) if err != nil { return err } if err := json.Unmarshal(data, external); err != nil { return err } if err := s.converter.Convert(external, obj, 0, s.generateConvertMeta(dataVersion, objVersion)); err != nil { return err } return s.SetVersionAndKind("", "", obj) }
package log import ( "testing" ) type testLogger struct { keyvals []interface{} } func (tl *testLogger) Log(keyvals ...interface{}) error { tl.keyvals = keyvals return nil } type testSink struct { keyvals []interface{} } func (ts *testSink) Receive(keyvals ...interface{}) error { ts.keyvals = keyvals return nil } func TestLogger_Event(t *testing.T) { ts := &testSink{} tl := &testLogger{} l := NewLogger(tl, []EventSink{ts}) l.Event("important_event", "act_on_me") if len(ts.keyvals) != 2 { t.Errorf("Expected to recieve event with 2 values, got %v", len(ts.keyvals)) } m1 := ts.keyvals[0] m2 := ts.keyvals[1] if m1.(string) != "important_event" || m2.(string) != "act_on_me" { t.Errorf("Expected [important_event, act_on_me] but got %s", ts.keyvals) } } func TestLogger_Log(t *testing.T)
{ tl := &testLogger{} l := NewLogger(tl, nil) l.Log("message", "value") if len(tl.keyvals) != 2 { t.Errorf("Expected log message with 2 values, got %v", len(tl.keyvals)) } m1 := tl.keyvals[0] m2 := tl.keyvals[1] if m1.(string) != "message" || m2.(string) != "value" { t.Errorf("Expected [message, value] but got %s", tl.keyvals) } }
package main import "reflect" var a, b int func chanreflect1() { ch := make(chan *int, 0) crv := reflect.ValueOf(ch) crv.Send(reflect.ValueOf(&a)) print(crv.Interface()) print(crv.Interface().(chan *int)) print(<-ch) } func main() { chanreflect1() chanreflect2() } func chanreflect2()
{ ch := make(chan *int, 0) ch <- &b crv := reflect.ValueOf(ch) r, _ := crv.Recv() print(r.Interface()) print(r.Interface().(*int)) }
package godo import ( "context" "net/http" "time" ) const billingHistoryBasePath = "v2/customers/my/billing_history" type BillingHistoryService interface { List(context.Context, *ListOptions) (*BillingHistory, *Response, error) } type BillingHistoryServiceOp struct { client *Client } var _ BillingHistoryService = &BillingHistoryServiceOp{} type BillingHistory struct { BillingHistory []BillingHistoryEntry `json:"billing_history"` Links *Links `json:"links"` Meta *Meta `json:"meta"` } type BillingHistoryEntry struct { Description string `json:"description"` Amount string `json:"amount"` InvoiceID *string `json:"invoice_id"` InvoiceUUID *string `json:"invoice_uuid"` Date time.Time `json:"date"` Type string `json:"type"` } func (s *BillingHistoryServiceOp) List(ctx context.Context, opt *ListOptions) (*BillingHistory, *Response, error) { path, err := addOptions(billingHistoryBasePath, opt) if err != nil { return nil, nil, err } req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil) if err != nil { return nil, nil, err } root := new(BillingHistory) resp, err := s.client.Do(ctx, req, root) if err != nil { return nil, resp, err } if l := root.Links; l != nil { resp.Links = l } if m := root.Meta; m != nil { resp.Meta = m } return root, resp, err } func (b BillingHistory) String() string
{ return Stringify(b) }
package govaluate type lexerStream struct { source []rune position int length int } func newLexerStream(source string) *lexerStream { var ret *lexerStream var runes []rune for _, character := range source { runes = append(runes, character) } ret = new(lexerStream) ret.source = runes ret.length = len(runes) return ret } func (l *lexerStream) rewind(amount int) { l.position -= amount } func (l lexerStream) canRead() bool { return l.position < l.length } func (l *lexerStream) readCharacter() rune
{ var character rune character = l.source[l.position] l.position++ return character }
package townsita import ( "encoding/json" "log" "os" ) const defaultConfigFile = "./config/townsita.json" type Config struct{} func NewConfig() *Config { return &Config{} } func (c *Config) templatePath(templateName string) string { return "./templates/" + templateName } func (c *Config) Load(args []string) error
{ fileName := defaultConfigFile if len(args) > 1 { fileName = args[1] } log.Printf("Loading config from %s", fileName) file, err := os.Open(fileName) if err != nil { return err } decoder := json.NewDecoder(file) if err := decoder.Decode(c); err != nil { return err } return nil }
package iso20022 type PlainCardData4 struct { PAN *Min8Max28NumericText `xml:"PAN"` CardSequenceNumber *Min2Max3NumericText `xml:"CardSeqNb,omitempty"` EffectiveDate *Max10Text `xml:"FctvDt,omitempty"` ExpiryDate *Max10Text `xml:"XpryDt"` ServiceCode *Exact3NumericText `xml:"SvcCd,omitempty"` TrackData []*TrackData1 `xml:"TrckData,omitempty"` CardSecurityCode *CardSecurityInformation1 `xml:"CardSctyCd,omitempty"` } func (p *PlainCardData4) SetPAN(value string) { p.PAN = (*Min8Max28NumericText)(&value) } func (p *PlainCardData4) SetCardSequenceNumber(value string) { p.CardSequenceNumber = (*Min2Max3NumericText)(&value) } func (p *PlainCardData4) SetEffectiveDate(value string) { p.EffectiveDate = (*Max10Text)(&value) } func (p *PlainCardData4) SetExpiryDate(value string) { p.ExpiryDate = (*Max10Text)(&value) } func (p *PlainCardData4) SetServiceCode(value string) { p.ServiceCode = (*Exact3NumericText)(&value) } func (p *PlainCardData4) AddTrackData() *TrackData1 { newValue := new(TrackData1) p.TrackData = append(p.TrackData, newValue) return newValue } func (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1
{ p.CardSecurityCode = new(CardSecurityInformation1) return p.CardSecurityCode }
package main import "bufio" import "crypto/tls" import "fmt" import "net" func main() { Dial(":1025", ConfigTLS("ccert", "ckey"), func(c net.Conn) { if m, e := bufio.NewReader(c).ReadString('\n'); e == nil { fmt.Printf(m) } }) } func ConfigTLS(c, k string) (r *tls.Config) { if cert, e := tls.LoadX509KeyPair(c, k); e == nil { r = &tls.Config{ Certificates: []tls.Certificate{ cert }, InsecureSkipVerify: true, } } return } func Dial(a string, conf *tls.Config, f func(net.Conn))
{ if c, e := tls.Dial("tcp", a, conf); e == nil { defer c.Close() f(c) } }
package numericword import ( "fmt" ) var ( bigkeys = []int64{ 1000000000000000000, 1000000000000000, 1000000000000, 1000000000, 1000000, 1000, 100} bignames = map[int64]string{ 1000000000000000000: "quintillion", 1000000000000000: "quadrillion", 1000000000000: "trillion", 1000000000: "billion", 1000000: "million", 1000: "thousand", 100: "hundred"} tens = []string{ "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} ones = []string{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} ) func ToWords(i int64) string { if i < 0 { return fmt.Sprintf("negative %s", convert(-1*i)) } return convert(i) } func convert(i int64) string
{ if i < 20 { return ones[i] } else if i < 100 && i%10 == 0 { return tens[i/10] } else if i < 100 { return fmt.Sprintf("%s %s", tens[i/10], convert(i%10)) } for j := 0; j < len(bigkeys); j++ { place := bigkeys[j] if i >= place { if i%place == 0 { return fmt.Sprintf("%s %s", convert(i/place), bignames[place]) } else { return fmt.Sprintf("%s %s %s", convert(i/place), bignames[place], convert(i%place)) } } } return "oops" }
package jsonutil import ( "github.com/buger/jsonparser" "strconv" ) func GetString(data []byte, keys ...string) (string, error) { return jsonparser.GetString(data, keys...) } func MustGetString(data []byte, keys ...string) string { s, err := GetString(data, keys...) if err != nil { return "" } return s } func GetFloat(data []byte, keys ...string) (float64, error) { return jsonparser.GetFloat(data, keys...) } func MustGetFloat(data []byte, keys ...string) float64 { f, err := GetFloat(data, keys...) if err != nil { return 0.0 } return f } func MustGetInt(data []byte, keys ...string) int64 { i, err := GetInt(data, keys...) if err != nil { if s := MustGetString(data, keys...); len(s) == 0 { return 0 } else if i, err = strconv.ParseInt(s, 10, 64); err != nil { return 0 } } return i } func GetBoolean(data []byte, keys ...string) (bool, error) { return jsonparser.GetBoolean(data, keys...) } func MustGetBoolean(data []byte, keys ...string) bool { b, err := GetBoolean(data, keys...) if err != nil { return false } return b } func GetInt(data []byte, keys ...string) (int64, error)
{ return jsonparser.GetInt(data, keys...) }
package update import ( "github.com/spf13/cobra" "github.com/emicklei/go-restful/log" "github.com/kubernetes-incubator/apiserver-builder/cmd/apiserver-boot/boot/init_repo" ) var vendorCmd = &cobra.Command{ Use: "vendor", Short: "Update the vendor packages managed by apiserver-builder.", Long: `Update the vendor packages managed by apiserver-builder.`, Example: `# Replace the vendor packages managed by apiserver-builder with versions for the current install. apiserver-boot update vendor `, Run: RunUpdateVendor, } func RunUpdateVendor(cmd *cobra.Command, args []string) { init_repo.Update = true log.Printf("Replacing vendored libraries managed by apiserver-builder with the current version.") init_repo.CopyGlide() } func AddUpdateVendorCmd(cmd *cobra.Command)
{ cmd.AddCommand(vendorCmd) }
package testutils type BlockingRW struct{ nilChan chan struct{} } func (rw *BlockingRW) Read(p []byte) (n int, err error) { <-rw.nilChan return } type NoopRW struct{} func (rw *NoopRW) Read(p []byte) (n int, err error) { return len(p), nil } func (rw *NoopRW) Write(p []byte) (n int, err error) { return len(p), nil } func (rw *BlockingRW) Write(p []byte) (n int, err error)
{ <-rw.nilChan return }
package caaa import ( "encoding/xml" "github.com/fgrid/iso20022" ) type Document00900101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document"` Message *AcceptorReconciliationRequestV01 `xml:"AccptrRcncltnReq"` } type AcceptorReconciliationRequestV01 struct { Header *iso20022.Header1 `xml:"Hdr"` ReconciliationRequest *iso20022.AcceptorReconciliationRequest1 `xml:"RcncltnReq"` SecurityTrailer *iso20022.ContentInformationType3 `xml:"SctyTrlr"` } func (a *AcceptorReconciliationRequestV01) AddHeader() *iso20022.Header1 { a.Header = new(iso20022.Header1) return a.Header } func (a *AcceptorReconciliationRequestV01) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest1 { a.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest1) return a.ReconciliationRequest } func (a *AcceptorReconciliationRequestV01) AddSecurityTrailer() *iso20022.ContentInformationType3 { a.SecurityTrailer = new(iso20022.ContentInformationType3) return a.SecurityTrailer } func (d *Document00900101) AddMessage() *AcceptorReconciliationRequestV01
{ d.Message = new(AcceptorReconciliationRequestV01) return d.Message }
package template import ( "github.com/dpb587/metalink" ) type templateFile metalink.File func (tf templateFile) SHA1() string { for _, hash := range tf.Hashes { if hash.Type == "sha-1" { return hash.Hash } } return "" } func (tf templateFile) SHA256() string { for _, hash := range tf.Hashes { if hash.Type == "sha-256" { return hash.Hash } } return "" } func (tf templateFile) SHA512() string { for _, hash := range tf.Hashes { if hash.Type == "sha-512" { return hash.Hash } } return "" } func (tf templateFile) MD5() string
{ for _, hash := range tf.Hashes { if hash.Type == "md5" { return hash.Hash } } return "" }
package main import ( "testing" ) func TestMatchWithTag(t *testing.T) { isMatch := matchesReference("gcr.io/pause:latest", "pause:latest") if !isMatch { t.Error("expected match, got not match") } isMatch = matchesReference("gcr.io/pause:latest", "kubernetes/pause:latest") if isMatch { t.Error("expected not match, got match") } } func TestNoMatchesReferenceWithTag(t *testing.T) { isMatch := matchesReference("gcr.io/pause:latest", "redis:latest") if isMatch { t.Error("expected no match, got match") } isMatch = matchesReference("gcr.io/pause:latest", "kubernetes/redis:latest") if isMatch { t.Error("expected no match, got match") } } func TestMatchesReferenceWithoutTag(t *testing.T) { isMatch := matchesReference("gcr.io/pause:latest", "pause") if !isMatch { t.Error("expected match, got not match") } isMatch = matchesReference("gcr.io/pause:latest", "kubernetes/pause") if isMatch { t.Error("expected not match, got match") } } func TestNoMatchesReferenceWithoutTag(t *testing.T) { isMatch := matchesReference("gcr.io/pause:latest", "redis") if isMatch { t.Error("expected no match, got match") } isMatch = matchesReference("gcr.io/pause:latest", "kubernetes/redis") if isMatch { t.Error("expected no match, got match") } } func TestSizeFormatting(t *testing.T)
{ size := formattedSize(0) if size != "0 B" { t.Errorf("Error formatting size: expected '%s' got '%s'", "0 B", size) } size = formattedSize(1000) if size != "1 KB" { t.Errorf("Error formatting size: expected '%s' got '%s'", "1 KB", size) } size = formattedSize(1000 * 1000 * 1000 * 1000) if size != "1 TB" { t.Errorf("Error formatting size: expected '%s' got '%s'", "1 TB", size) } }
package insights import "github.com/Azure/azure-sdk-for-go/version" func UserAgent() string { return "Azure-SDK-For-Go/" + version.Number + " insights/2015-05-01" } func Version() string
{ return version.Number }
package task import ( "fmt" ) type Event struct { Task *Task Payload interface{} } func (e *Event) String() string { return fmt.Sprintf("%T{from %v: %v}", e, e.Task, e.Payload) } type Ended struct { Error error } type Output struct { Chunk string } func (p *Output) String() string { return fmt.Sprintf("%T{%v}", p, p.Chunk) } func (p *Ended) String() string
{ return fmt.Sprintf("%T{%v}", p, p.Error) }
package building import "fmt" type Single struct { prefix string option string } func (s Single) IsPresent() bool { return s.option != "" } func (s Single) Build() string { return fmt.Sprintf("%s %s", s.prefix, s.option) } func NewSingleBuilder(prefix, value string) Single
{ return Single{prefix, value} }
package main import ( "fmt" "log" "net/http" "os" "github.com/teddywing/new-house-on-the-block/purchase" ) func sendTokenToBuyer() error { transaction_id, err := purchase.SendMoney(os.Getenv("SELLER_COINBASE_KEY"), os.Getenv("SELLER_COINBASE_SECRET"), "mqy3kT6aFHymTcvmdwZLKq1Svo2m6sUtzH", "0.0001") if err != nil { return err } else { fmt.Println(transaction_id) return nil } } func main() { fs := http.FileServer(http.Dir("static")) http.Handle("/", fs) http.HandleFunc("/buy/", func(w http.ResponseWriter, r *http.Request) { var err error err = sendMoneyToSeller() if err != nil { log.Println(err) } err = sendTokenToBuyer() if err != nil { log.Println(err) } http.Redirect(w, r, "http://testsite.perfectburpee.com/new-house-on-the-block-page6/", 302) }) log.Println("Listening on port 3000") http.ListenAndServe(":3000", nil) } func sendMoneyToSeller() error
{ transaction_id, err := purchase.SendMoney(os.Getenv("COINBASE_KEY"), os.Getenv("COINBASE_SECRET"), "n2Qd6da1jiFgij5SSncFKh7MoFN74GdUxv", "0.0001") if err != nil { return err } else { fmt.Println(transaction_id) return nil } }
package model import ( "testing" ) func TestGetUsersById(t *testing.T) { user, err := GetUserByID(3) if err != nil { t.Fatal(err) } if user.FirstName != "Jonathan" { t.Errorf("should have returned the first name of %s", user.FirstName) } } func TestGetUsers(t *testing.T)
{ users := GetUsers() if len(users) != 50 { t.Errorf("Should have returned a list of 50 users") } }
package csi_test import ( "fmt" "os" "strings" "testing" gofigCore "github.com/akutz/gofig" gofig "github.com/akutz/gofig/types" ) func init() { r := gofigCore.NewRegistration("MapTest") r.Key(gofig.String, "", "", "", "nfs.volumes") gofigCore.Register(r) } func TestGofigMap(t *testing.T)
{ config := gofigCore.NewConfig(false, false, "config", "yaml") config.ReadConfig(strings.NewReader(` nfs: volumes: - name1=uri1 - name2=uri2 - name3=uri3 `)) asSlice := config.GetStringSlice("nfs.volumes") fmt.Printf("GetStringSlice: len=%d, %v\n", len(asSlice), asSlice) os.Setenv("NFS_VOLUMES", "name4=uri4 name5=uri5") asSlice = config.GetStringSlice("nfs.volumes") fmt.Printf("GetStringSlice: len=%d, %v\n", len(asSlice), asSlice) }
package assert import ( "bytes" "fmt" "github.com/alecthomas/colour" "github.com/alecthomas/repr" "github.com/sergi/go-diff/diffmatchpatch" ) func DiffValues(a, b interface{}) string { printer := colour.String() diff := diffmatchpatch.New() at := repr.String(a, repr.OmitEmpty()) bt := repr.String(b, repr.OmitEmpty()) diffs := diff.DiffMain(at, bt, true) for _, d := range diffs { switch d.Type { case diffmatchpatch.DiffEqual: if len(d.Text) <= 40 { printer.Print(d.Text) } else { printer.Printf("%s^B...^R%s", d.Text[:15], d.Text[len(d.Text)-15:]) } case diffmatchpatch.DiffDelete: printer.Printf("^9%s^R", d.Text) case diffmatchpatch.DiffInsert: printer.Printf("^a%s^R", d.Text) } } return printer.String() } func DiffValuesDefault(a, b interface{}) string
{ diff := diffmatchpatch.New() at := repr.String(a) bt := repr.String(b) diffs := diff.DiffMain(at, bt, true) w := bytes.NewBuffer(nil) for _, d := range diffs { switch d.Type { case diffmatchpatch.DiffEqual: if len(d.Text) <= 40 { w.WriteString(d.Text) } else { fmt.Fprintf(w, "%s...%s", d.Text[:15], d.Text[len(d.Text)-15:]) } case diffmatchpatch.DiffDelete: fmt.Fprintf(w, "-{{%s}}", d.Text) case diffmatchpatch.DiffInsert: fmt.Fprintf(w, "+{{%s}}", d.Text) } } return w.String() }
package fractal import ( "reflect" "github.com/nsf/termbox-go" "testing" ) func TestFrameProxyMan(t *testing.T) { myManual := Manual{ Summary: "sup", Keys: KeyMap{ termbox.Event{Ch: 'j'}: { ID: "wow", Description: "now", }, }, } handler := &TestHandler{Manual: myManual} if !reflect.DeepEqual(handler.Man(), NewFrameProxy(handler, 0, 0).Man()) { t.Errorf("did not proxy Man correctly") } } func TestFrameProxyCursor(t *testing.T)
{ handler := &TestHandler{} proxy := NewFrameProxy(handler, 0, 0) proxy.Frame.bwidth, proxy.Frame.bheight = 2, 2 offsetCursor := handler.GetCursor() offsetCursor.X++ offsetCursor.Y++ if offsetCursor != proxy.GetCursor() { t.Errorf("did not proxy GetCursor correctly") } }
package oauth import ( "fmt" "net/http" ) func (c oauthClient) AvatarURL(userID uint, size int, fallback bool) (string, error) { url := fmt.Sprintf( "%s/avatar?user_id=%d", c.apiURL, userID, ) if size > 0 { if !c.validSize(size) { return "", fmt.Errorf("Invalid size: %d", size) } url = fmt.Sprintf( "%s&size=%d", url, size, ) } if !fallback { url = fmt.Sprintf( "%s&fallback=%t", url, fallback, ) } req, err := c.newGetRequest(url) if err != nil { return "", err } c.logRequest(req) resp, err := http.DefaultTransport.RoundTrip(req) if err != nil { return "", err } if resp != nil { c.logResponse(resp) } if fallback { if resp.StatusCode != http.StatusFound { return "", fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusFound) } } else { if resp.StatusCode == http.StatusNoContent { return "", nil } if resp.StatusCode != http.StatusFound { return "", fmt.Errorf("Unexpected response code %d - expected either %d or %d", resp.StatusCode, http.StatusNoContent, http.StatusFound) } } location, err := resp.Location() if err != nil { return "", err } return location.String(), nil } func (c oauthClient) validSize(size int) bool
{ validSizes := []int{25, 28, 30, 32, 50, 54, 56, 60, 64, 108, 128, 135, 256, 270, 512} for _, s := range validSizes { if s == size { return true } } return false }
package main import ( "bytes" "fmt" "log" ) type Address struct { Street, City string } type Person struct { FirstName, LastName string } type T1 string type T2 string type T3 string var logger *log.Logger func main() { myAddress := Address{ Street: "Trimveien 6", City: "Oslo", } log.Println(myAddress) me := Person{ FirstName: "Christian", LastName: "Bergum Bergersen", } log.Println(me) var foo T1 foo = "foo" log.Println(foo) var bar T3 bar = "bar" log.Println(bar) } func (address Address) String() string { return fmt.Sprintf("%s", address) } func (t1 T1) String() string { return fmt.Sprint(t1) } func (t2 T2) String() string { log.Print("Calling String() for : %v", t2) return fmt.Sprintln(t2) } func (bar T3) String() string { var buf bytes.Buffer logger = log.New(&buf, "logger: ", log.Lshortfile) logger.Printf("Calling String() for %+v", bar) return fmt.Sprintf("Bar") } func (person Person) String() string
{ return fmt.Sprintf("%s %s", person.FirstName, person.LastName) }
package main import ( "fmt" "html/template" "net/http" "strings" "log" ) func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) if r.Method == "GET" { t, _ := template.ParseFiles("login.gtpl") t.Execute(w, nil) } else { r.ParseForm() fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) } } func main() { http.HandleFunc("/", sayHelloName) http.HandleFunc("/login", login) err := http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("ListenAndServe:", err) } } func sayHelloName(w http.ResponseWriter, r *http.Request)
{ r.ParseForm() fmt.Println("---------------------------") fmt.Println("Form", r.Form) fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) for k, v := range r.Form { fmt.Println(k, "=", strings.Join(v, "")) } fmt.Fprintf(w, "Hello!!" + strings.Join(r.Form["name"], "")) }
package cdsclient import ( "context" "github.com/ovh/cds/sdk" ) func (c *client) VCSConfiguration() (map[string]sdk.VCSConfiguration, error)
{ var vcsServers map[string]sdk.VCSConfiguration if _, err := c.GetJSON(context.Background(), "/config/vcs", &vcsServers); err != nil { return nil, err } return vcsServers, nil }
package cluster_test import ( "fmt" "testing" "github.com/influxdb/influxdb/cluster" "github.com/influxdb/influxdb/services/meta" ) func NewNodes() []meta.NodeInfo { var nodes []meta.NodeInfo for i := 1; i <= 2; i++ { nodes = append(nodes, meta.NodeInfo{ ID: uint64(i), Host: fmt.Sprintf("localhost:999%d", i), }) } return nodes } func TestBalancerUp(t *testing.T) { nodes := NewNodes() b := cluster.NewNodeBalancer(nodes) first := b.Next() if first == nil { t.Errorf("expected datanode, got %v", first) } second := b.Next() if second == nil { t.Errorf("expected datanode, got %v", second) } if first.ID == second.ID { t.Errorf("expected first != second. got %v = %v", first.ID, second.ID) } } func TestBalancerEmptyNodes(t *testing.T)
{ b := cluster.NewNodeBalancer([]meta.NodeInfo{}) got := b.Next() if got != nil { t.Errorf("expected nil, got %v", got) } }
package clock import "time" var Work Clock func init() { Work = New() } func Now() time.Time { return Work.Now() } func Since(t time.Time) time.Duration { return Work.Now().Sub(t) } func Sleep(d time.Duration) { Work.Sleep(d) } func After(d time.Duration) <-chan time.Time { return Work.After(d) } func Ticker(d time.Duration) *time.Ticker { return Work.Ticker(d) } type Clock interface { Now() time.Time Sleep(d time.Duration) After(d time.Duration) <-chan time.Time Tick(d time.Duration) <-chan time.Time Ticker(d time.Duration) *time.Ticker } type Mock interface { Clock Set(t time.Time) Mock Add(d time.Duration) Mock Freeze() Mock IsFrozen() bool Unfreeze() Mock Close() } func Tick(d time.Duration) <-chan time.Time
{ return Work.Tick(d) }
package sw import ( "crypto/rsa" "crypto/sha256" "crypto/x509" "errors" "fmt" "github.com/hyperledger/fabric/bccsp" ) type rsaPublicKey struct{ pubKey *rsa.PublicKey } func (k *rsaPublicKey) Symmetric() bool { return false } func (k *rsaPublicKey) Private() bool { return false } func (k *rsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil } func (k *rsaPublicKey) Bytes() (raw []byte, err error) { if k.pubKey == nil { return nil, errors.New("Failed marshalling key. Key is nil.") } raw, err = x509.MarshalPKIXPublicKey(k.pubKey) if err != nil { return nil, fmt.Errorf("Failed marshalling key [%s]", err) } return } func (k *rsaPublicKey) SKI() []byte
{ if k.pubKey == nil { return nil } raw := x509.MarshalPKCS1PublicKey(k.pubKey) hash := sha256.Sum256(raw) return hash[:] }
package lib import "sync" type ConcurrentPrinterMap struct { byCUPSName map[string]Printer byGCPID map[string]Printer mutex sync.RWMutex } func NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap { cpm := ConcurrentPrinterMap{} cpm.Refresh(printers) return &cpm } func (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer) { c := make(map[string]Printer, len(newPrinters)) for _, printer := range newPrinters { c[printer.Name] = printer } g := make(map[string]Printer, len(newPrinters)) for _, printer := range newPrinters { if len(printer.GCPID) > 0 { g[printer.GCPID] = printer } } cpm.mutex.Lock() defer cpm.mutex.Unlock() cpm.byCUPSName = c cpm.byGCPID = g } func (cpm *ConcurrentPrinterMap) GetByCUPSName(name string) (Printer, bool) { cpm.mutex.RLock() defer cpm.mutex.RUnlock() if p, exists := cpm.byCUPSName[name]; exists { return p, true } return Printer{}, false } func (cpm *ConcurrentPrinterMap) GetAll() []Printer { cpm.mutex.RLock() defer cpm.mutex.RUnlock() printers := make([]Printer, len(cpm.byCUPSName)) i := 0 for _, printer := range cpm.byCUPSName { printers[i] = printer i++ } return printers } func (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool)
{ cpm.mutex.RLock() defer cpm.mutex.RUnlock() if p, exists := cpm.byGCPID[gcpID]; exists { return p, true } return Printer{}, false }
package logging type DefaultFormatter struct { } func (f *DefaultFormatter) GetPrefix(lvl level) string { return "" } func (f *DefaultFormatter) Format(lvl level, v ...interface{}) []interface{} { return append([]interface{}{header()}, v...) } func (f *DefaultFormatter) GetSuffix(lvl level) string
{ return "" }
package resources import "github.com/awslabs/goformation/cloudformation/policies" type AWSAmazonMQBroker_MaintenanceWindow struct { DayOfWeek string `json:"DayOfWeek,omitempty"` TimeOfDay string `json:"TimeOfDay,omitempty"` TimeZone string `json:"TimeZone,omitempty"` _deletionPolicy policies.DeletionPolicy _dependsOn []string _metadata map[string]interface{} } func (r *AWSAmazonMQBroker_MaintenanceWindow) AWSCloudFormationType() string { return "AWS::AmazonMQ::Broker.MaintenanceWindow" } func (r *AWSAmazonMQBroker_MaintenanceWindow) DependsOn() []string { return r._dependsOn } func (r *AWSAmazonMQBroker_MaintenanceWindow) Metadata() map[string]interface{} { return r._metadata } func (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) { r._metadata = metadata } func (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) { r._deletionPolicy = policy } func (r *AWSAmazonMQBroker_MaintenanceWindow) SetDependsOn(dependencies []string)
{ r._dependsOn = dependencies }
package etcd2 import ( "fmt" "time" "github.com/coreos/etcd/client" "golang.org/x/net/context" ) type Etcd2Connect struct { etcd2 client.Client } func (e *Etcd2Connect) Set(data map[string]string) error { kapi := client.NewKeysAPI(e.etcd2) for k, v := range data { if _, err := kapi.Set(context.Background(), k, v, nil); err != nil { return err } } return nil } func (e *Etcd2Connect) Make(data map[string]string) error { kapi := client.NewKeysAPI(e.etcd2) opts := &client.SetOptions{PrevExist: client.PrevNoExist} for k, v := range data { if _, err := kapi.Set(context.Background(), k, v, opts); err != nil { return err } } return nil } func (e *Etcd2Connect) Get(data map[string]string) (map[string]string, error) { kapi := client.NewKeysAPI(e.etcd2) result := make(map[string]string) for k := range data { resp, err := kapi.Get(context.Background(), k, nil) if err != nil { return nil, err } result[k] = resp.Node.Value } return result, nil } func NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error)
{ c, err := client.New(client.Config{ Endpoints: []string{fmt.Sprintf("http://%s", etcd2EndPoint)}, Transport: client.DefaultTransport, HeaderTimeoutPerRequest: time.Second, }) if err != nil { return nil, err } return &Etcd2Connect{etcd2: c}, nil }
package utils import ( "errors" "fmt" "github.com/heketi/heketi/tests" "testing" "time" ) func TestStatusGroupSuccess(t *testing.T) { s := NewStatusGroup() max := 100 s.Add(max) for i := 0; i < max; i++ { go func(value int) { defer s.Done() time.Sleep(time.Millisecond * 1 * time.Duration(value)) }(i) } err := s.Result() tests.Assert(t, err == nil) } func TestStatusGroupFailure(t *testing.T) { s := NewStatusGroup() for i := 0; i < 100; i++ { s.Add(1) go func(value int) { defer s.Done() time.Sleep(time.Millisecond * 1 * time.Duration(value)) if value%10 == 0 { s.Err(errors.New(fmt.Sprintf("Err: %v", value))) } }(i) } err := s.Result() tests.Assert(t, err != nil) tests.Assert(t, err.Error() == "Err: 90", err) } func TestNewStatusGroup(t *testing.T)
{ s := NewStatusGroup() tests.Assert(t, s != nil) tests.Assert(t, s.results != nil) tests.Assert(t, len(s.results) == 0) tests.Assert(t, s.err == nil) }
package util import ( "os" "syscall" "time" ) func FsTime(info os.FileInfo) []time.Time
{ ret := make([]time.Time, 3, 3) attr := info.Sys().(*syscall.Win32FileAttributeData) ret[0] = time.Unix(0, attr.CreationTime.Nanoseconds()) ret[1] = time.Unix(0, attr.LastWriteTime.Nanoseconds()) ret[2] = time.Unix(0, attr.LastAccessTime.Nanoseconds()) return ret }