func String(s fmt.Stringer) string { if reflect.ValueOf(s).IsNil() { return "" } return s.String() }
func TestGraphSupportsDownCasting(t *testing.T) { RegisterTestingT(t) graph := inject.NewGraph() var ( d fmt.Stringer ) graph.Define(&d, inject.NewProvider(NewD)) graph.ResolveAll() Expect(d).To(Equal(NewD())) Expect(d.String()).To(Equal("&ImplD{}")) expectedString := `&graph\{ definitions: \[ &definition\{ ptr: \*fmt\.Stringer=0x.*, provider: &provider\{ constructor: func\(\) \*test\.ImplD, argPtrs: \[\] \}, value: <\*test\.ImplD Value> \} \] \}` Expect(graph.String()).To(MatchRegexp(expectedString)) }
func TestInterfaces(t *testing.T) { db, err := bolt.Open("my4.db", 0600, nil) if err != nil { t.Error(err.Error()) } defer os.Remove("my4.db") defer db.Close() s := NewStore(db, []byte("interface")) var j fmt.Stringer = &MyType{"First", "Last"} s.Put([]byte("test"), &j) err = s.ForEach(func(str fmt.Stringer) { if str.String() != "First Last" { t.Errorf("unexpected string %s", str) } }) if err != nil { t.Error(err.Error()) } var i fmt.Stringer err = s.Get([]byte("test"), &i) if err != nil { t.Error(err.Error()) } else { if i.String() != "First Last" { t.Errorf("unexpected string %s", i) } } }
// Insert adds a new item to the hash map or, if the key already exists, // replaces the current item with the new one. func (pm *ParMap) Insert(item fmt.Stringer) { key := item.String() shard := pm.getShard(key) shard.mutex.Lock() shard.index[key] = item shard.mutex.Unlock() }
func testStringMatch(t *testing.T, s fmt.Stringer, expected string) { actual := strings.TrimSpace(s.String()) expected = strings.TrimSpace(expected) if actual != expected { t.Fatalf("Actual\n\n%s\n\nExpected:\n\n%s", actual, expected) } }
func assert(t *testing.T, o fmt.Stringer, s string) { if o.String() != s { t.Log("Expected object to be resolved differently as a String:") t.Logf("Object: %#v", o) t.Logf("Expected: %q", s) t.Fatalf("Got: %q", o.String()) } }
func (v *ASTStringer) AddWithFallback(color string, what fmt.Stringer, fallback string) *ASTStringer { if !isNil(what) { v.AddStringColored(color, what.String()) } else { v.AddStringColored(color, fallback) } return v }
func (cLogger *commonLogger) processLogMsg(level LogLevel, message fmt.Stringer, context LogContextInterface) { defer func() { if err := recover(); err != nil { reportInternalError(fmt.Errorf("recovered from panic during message processing: %s", err)) } }() if cLogger.config.IsAllowed(level, context) { cLogger.config.RootDispatcher.Dispatch(message.String(), level, context, reportInternalError) } }
// Lookup finds the first node in the current scope by name. func (s *Scope) Lookup(token fmt.Stringer) (ssa.Node, error) { name := token.String() if s.Empty() { return nil, fmt.Errorf("can't find a node '%s' in an empty scope stack", name) } for _, symtab := range s.stack.list { if symtab.contains(name) { return symtab.get(name) } } return nil, fmt.Errorf("'%s' not yet declared", name) }
func safeString(str fmt.Stringer) (s string, ok bool) { defer func() { if panicVal := recover(); panicVal != nil { if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { s, ok = "null", false } else { panic(panicVal) } } }() s, ok = str.String(), true return }
func safeString(str fmt.Stringer) (s string) { defer func() { if panicVal := recover(); panicVal != nil { if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { s = "NULL" } else { panic(panicVal) } } }() s = str.String() return }
// Global sets a node and its name in the global scope. func (s *Scope) Global(token fmt.Stringer, n ssa.Node) error { name := token.String() symtab, err := s.stack.bottom() if err != nil { return err } if symtab.contains(name) { return fmt.Errorf("'%s' already declared globally", name) } err = symtab.set(name, n) if err != nil { return err } return nil }
func (cLogger *commonLogger) processLogMsg( level LogLevel, message fmt.Stringer, context logContextInterface) { defer func() { if err := recover(); err != nil { fmt.Println(err) } }() if cLogger.config.IsAllowed(level, context) { cLogger.config.RootDispatcher.Dispatch(message.String(), level, context, reportInternalError) } }
// Add adds a name to the topmost scope in the scope stack. func (s *Scope) Add(token fmt.Stringer, n ssa.Node) error { name := token.String() if s.Contains(name) { return fmt.Errorf("'%s' already declared", name) } symtab, err := s.stack.peek() if err != nil { return err } err = symtab.set(name, n) if err != nil { return err } return nil }
func TestNXTStringer(t *testing.T) { name, devicePath := "testingbot", "/dev/tty-foobar" var n fmt.Stringer n = NewNXT(name, devicePath) if n == nil { t.Errorf("Calling NewNXT should not result in a nil NXT instance.") return } expected, actual := fmt.Sprintf("NXT \"%s\": %s", name, devicePath), n.String() if actual != expected { t.Errorf("Expected NXT.String to return \"%s\", but got \"%s\" instead", expected, actual) } }
func (w *Web) pathDealer(re *regexp.Regexp, str fmt.Stringer) { names := re.SubexpNames() matches := re.FindStringSubmatch(str.String()) for key, name := range names { if name != "" { w.Param.Set(name, matches[key]) } } switch str.(type) { case pathStr: w.pri.curpath += matches[0] w.pri.path = w.pri.path[re.FindStringIndex(w.pri.path)[1]:] } }
// Trust takes a name token and node that has not yet been defined and "trusts" // that it will be defined later according to the node type values that were // implied by the parser. func (t *TBV) Trust(token fmt.Stringer, node ssa.Node) { name := token.String() if _, ok := t.table[name]; ok { // p.enter()("'" + name + "' is already being trusted.") } else { t.table[name] = node } }
// SendSync sends SYNC message to the writer, tagging it as sent from node, // described by given source and adding optional description for the given // SYNC phase taken by extraction it from the original SYNC message, sent // by node. func (protocol *syncProtocol) SendSync( source fmt.Stringer, sync string, ) error { data := strings.TrimSpace( strings.TrimPrefix(sync, protocol.prefix+" "+syncProtocolSync), ) _, err := io.WriteString( protocol.output, syncProtocolSync+" "+source.String()+" "+data+"\n", ) if err != nil { return protocolSuspendEOF(err) } return nil }
//AddValue ajoute dans la BD func (dbManager *DbManager) AddValue(bucketName string, key string, object fmt.Stringer) error { err := dbManager.db.Update(func(tx *bolt.Tx) error { bucket, err := tx.CreateBucketIfNotExists([]byte(bucketName)) if err != nil { return err } encoded := object.String() return bucket.Put([]byte(key), []byte(encoded)) }) if err == nil { logger.Print("Ajout de " + key + " dans la bd") } else { logger.Error("Erreur lors de l'ajout dans la bd", err) } return nil }
// Verify verifies that the provided token and node match with a corresponding // pair that were trusted previously. func (t *TBV) Verify(tok fmt.Stringer, node ssa.Node) (bool, error) { name := tok.String() // check if the node is present in the TBV table if trustNode, ok := t.table[name]; ok { if trustNode.Type() != node.Type() { return true, errors.New("mismatch types") } switch trustNode.Type().Token() { case token.FUNC: trustFuncType := trustNode.Type().(*types.Func) funcType := node.Type().(*types.Func) if trustFuncType.Value() != nil { if trustFuncType.Value() != funcType.Value() { return false, errors.New("The function '" + name + "' must return either a type " + trustFuncType.Value().String() + " or " + funcType.Value().String() + ". Not both.") } } if trustFuncType.Arity() != funcType.Arity() { return false, errors.New("Number of arguments do not match.") } trustParam := trustFuncType.Param() param := funcType.Param() for param != nil { if param != trustParam { return false, errors.New("Parameter types are off.") } param = param.Next() trustParam = trustParam.Next() } return true, nil } } return false, nil }
func (self *defaultLogger) output(s Severity, msg fmt.Stringer) { if s > self.severity { return } self.mu.Lock() defer self.mu.Unlock() ctx := newRuntimeContext(s, msg.String(), time.Now()) final := bytes.NewBufferString(self.formatter.Format(ctx)) if !bytes.HasSuffix(final.Bytes(), []byte("\n")) { final.WriteString("\n") } if err := self.out.Dispatch(s, final.Bytes()); err != nil { fmt.Fprintf(os.Stderr, "Couldn't dispatch msg (%s): %s\n", final, err) return } if s == SeverityFatal { fmt.Fprintf(os.Stderr, "Abort with backtrace for debugging purpose:\n%s\n", stack(false)) os.Exit(255) } }
// Contains checks if a token name appears in TBV table. func (t TBV) Contains(token fmt.Stringer) bool { name := token.String() _, ok := t.table[name] return ok }
func stringer(s fmt.Stringer) string { return s.String() }
// Value returns the value associated with this context for key func (p *testFromSuit) Value(key fmt.Stringer) interface{} { return p.vars[key.String()] }
// SetValue saves a value associated with this context for key func (p *testFromSuit) SetValue(key fmt.Stringer, value interface{}) { p.vars[key.String()] = value }
func main() { // int, float32, float64, string, bool, byte var a int a = 11 var hello string hello = "Hello, World!" var b byte b = 10 fmt.Println(hello) fmt.Printf("Number: %d\n", a) fmt.Println("Byte:", b) // run-time error //n := 0 //num := 100 / n //fmt.Println(num) // compile-time error //num := 100 / 0 //fmt.Println(num) //name := getName() //fmt.Println("Hello", name) //name = getName1() //fmt.Println("Hello", name) for i := 0; i < 10; i++ { fmt.Print(i) fmt.Print(" ") } fmt.Println() i := 0 switch i { default: fmt.Println("Default") case 0, 1: fmt.Println("Zero or One") // The line below is used when we want the code to fall through the case below //fallthrough case 2: fmt.Println("Two") } // infinite loop //for { //fmt.Println("Hello") //} for i := 1; i <= 100; i++ { fmt.Print(fizzbuzz(i)) fmt.Print(" ") } fmt.Println() var nums [5]int fmt.Println(nums) var x int = 10 var y int = 20 x, y = swap(x, y) fmt.Println(x, y) x, y = y, x fmt.Println(x, y) //var nums1 []int nums1 := []int{} nums1 = append(nums1, 1) nums1 = append(nums1, 9) nums1 = append(nums1, 2, 3) fmt.Println(nums1) nums2 := [5]int{1, 2, 3, 4, 5} var slice []int slice = nums2[:3] slice[1] = 999 fmt.Println(nums2) fmt.Println(slice) nums3 := []int{1, 2, 3, 4, 5} var slice1 []int slice1 = append(slice1, nums3...) fmt.Println(nums3) fmt.Println(slice1) //m := map[string]string{} m := make(map[string]string) m["name"] = "Kan" m["company"] = "Pronto Marketing" fmt.Println(m) //m1 := map[string]map[string]string{ //"p1": map[string]string{ //"name": "Kan", //}, //} m1 := map[string]map[string]string{ "p1": { "name": "Kan", }, } fmt.Println(m1) arr := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} fmt.Println(arr) fmt.Println(arr[:]) results := []int{} results = even(arr[:]) fmt.Println(results) fmt.Println(arr) //var add func(int, int) int = func(a, b int) int { var add = func(a, b int) int { return a + b } fmt.Println(add(9, 9)) fmt.Println(filter(func(n int) bool { return n%2 == 0 }, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})) fmt.Println(filter(isEven, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})) num, err := div(100, 0) if err != nil { fmt.Println("Error:", err) //return } else { fmt.Println(num) } n := Num(10) n.printHello() //fmt.Println(n.String()) //fmt.Println(n) // If n does not implement String(), it will have error during the compile time var s fmt.Stringer s = n fmt.Println(s.String()) var s1 interface{} s1 = n //ss := s1.(fmt.Stringer) //fmt.Println(ss.String()) // Check if the interface can be converted into Stringer interface if ss, ok := s1.(fmt.Stringer); ok { fmt.Println(ss.String()) } // The other way to check interface // s.(type) can be used only with switch/case n2 := NumTest(30) var s2 interface{} s2 = n2 switch ss1 := s2.(type) { case fmt.Stringer: fmt.Println(ss1.String()) default: fmt.Printf("Not fmt.Stringer but is %T\n", s2) } c := Customer{ FirstName: "Kan", LastName: "Ouivirach", Age: 30, } fmt.Println(c) fmt.Println(c.Name()) c1 := AnotherCustomer{ firstName: "Kan", lastName: "Ouivirach", age: 30, } c1.SetFirstName("Pronto") fmt.Println(c1.Name()) }
// httpPost posts the req using the HTTP client. The call's method is // appended to the endpoint and set as the URL path. The call's arguments // are protobuf-serialized and written as the POST body. The content // type is set to application/x-protobuf. // // On success, the response body is unmarshalled into call.Reply. // // HTTP response codes which are retryable are retried with backoff in a loop // using the default retry options. Other errors sending HTTP request are // retried indefinitely using the same client command ID to avoid reporting // failure when in fact the command may go through and execute successfully. We // retry here to eventually get through with the same client command ID and be // given the cached response. func httpPost(c postContext, request, response gogoproto.Message, method fmt.Stringer) error { // Marshal the args into a request body. body, err := gogoproto.Marshal(request) if err != nil { return err } sharedClient, err := c.Context.GetHTTPClient() if err != nil { return err } // TODO(pmattis): Figure out the right thing to do here. The HTTP client we // get back from base.Context has a 3 second timeout. If a client operation // takes longer than that it will be retried. If we're not in an explicit // transaction the auto-transaction created on the server for the second // operation will be different than the still running first operation giving // them the potential to stomp on each other. client := *sharedClient client.Timeout = 60 * time.Second url := c.Context.HTTPRequestScheme() + "://" + c.Server + c.Endpoint + method.String() var ( req *http.Request resp *http.Response b []byte ) for r := retry.Start(c.RetryOpts); r.Next(); { req, err = http.NewRequest("POST", url, bytes.NewReader(body)) if err != nil { return err } req.Header.Add(util.ContentTypeHeader, util.ProtoContentType) req.Header.Add(util.AcceptHeader, util.ProtoContentType) req.Header.Add(util.AcceptEncodingHeader, util.SnappyEncoding) resp, err = client.Do(req) if err != nil { if log.V(1) { log.Warning(err) } continue } defer resp.Body.Close() switch resp.StatusCode { case http.StatusOK: // We're cool. case http.StatusServiceUnavailable, http.StatusGatewayTimeout, StatusTooManyRequests: // Retry on service unavailable and request timeout. // TODO(spencer): consider respecting the Retry-After header for // backoff / retry duration. continue default: // Can't recover from all other errors. return errors.New(resp.Status) } if resp.Header.Get(util.ContentEncodingHeader) == util.SnappyEncoding { resp.Body = &snappyReader{body: resp.Body} } b, err = ioutil.ReadAll(resp.Body) if err != nil { if log.V(1) { log.Warning(err) } continue } if err = gogoproto.Unmarshal(b, response); err != nil { if log.V(1) { log.Warning(err) } continue } break } return err }
func (connection Connection) Send(command fmt.Stringer) { connection.writeOut <- command.String() }
// Sign the given item and return a Signature func (pk PrivateKey) Sign(item fmt.Stringer) (Signature, error) { bytes := []byte(item.String()) return pk.SignBytes(bytes) }
func testMessageParse(t *testing.T, msg fmt.Stringer) { res := ParseMessage(msg.String()) t.Logf("Parsed message is %q", res) assert.AssertEquals(t, res[0], msg) }