id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
149,700
golang/gddo
database/database.go
Delete
func (db *Database) Delete(ctx context.Context, path string) error { c := db.Pool.Get() defer c.Close() id, err := redis.String(c.Do("HGET", "ids", path)) if err == redis.ErrNil { return nil } if err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil { return err } _, err = deleteScript.Do(c, path) return err }
go
func (db *Database) Delete(ctx context.Context, path string) error { c := db.Pool.Get() defer c.Close() id, err := redis.String(c.Do("HGET", "ids", path)) if err == redis.ErrNil { return nil } if err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil { return err } _, err = deleteScript.Do(c, path) return err }
[ "func", "(", "db", "*", "Database", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "id", ",", "err", ":=", "redis", ".", "String", "(", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ",", "path", ")", ")", "\n", "if", "err", "==", "redis", ".", "ErrNil", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "db", ".", "DeleteIndex", "(", "ctx", ",", "id", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "deleteScript", ".", "Do", "(", "c", ",", "path", ")", "\n", "return", "err", "\n", "}" ]
// Delete deletes the documentation for the given import path.
[ "Delete", "deletes", "the", "documentation", "for", "the", "given", "import", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L635-L652
149,701
golang/gddo
database/database.go
Block
func (db *Database) Block(root string) error { c := db.Pool.Get() defer c.Close() if _, err := c.Do("SADD", "block", root); err != nil { return err } // Remove all packages under the project root. keys, err := redis.Strings(c.Do("HKEYS", "ids")) if err != nil { return err } ctx := context.Background() for _, key := range keys { if key == root || strings.HasPrefix(key, root) && key[len(root)] == '/' { id, err := redis.String(c.Do("HGET", "ids", key)) if err != nil { return fmt.Errorf("cannot get package id for %s: %v", key, err) } if _, err := deleteScript.Do(c, key); err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil && err != search.ErrNoSuchDocument { return err } } } // Remove all packages in the newCrawl set under the project root. newCrawls, err := redis.Strings(c.Do("SORT", "newCrawl", "BY", "nosort")) if err != nil { return fmt.Errorf("cannot list newCrawl: %v", err) } for _, nc := range newCrawls { if nc == root || strings.HasPrefix(nc, root) && nc[len(root)] == '/' { if _, err := deleteScript.Do(c, nc); err != nil { return err } } } return nil }
go
func (db *Database) Block(root string) error { c := db.Pool.Get() defer c.Close() if _, err := c.Do("SADD", "block", root); err != nil { return err } // Remove all packages under the project root. keys, err := redis.Strings(c.Do("HKEYS", "ids")) if err != nil { return err } ctx := context.Background() for _, key := range keys { if key == root || strings.HasPrefix(key, root) && key[len(root)] == '/' { id, err := redis.String(c.Do("HGET", "ids", key)) if err != nil { return fmt.Errorf("cannot get package id for %s: %v", key, err) } if _, err := deleteScript.Do(c, key); err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil && err != search.ErrNoSuchDocument { return err } } } // Remove all packages in the newCrawl set under the project root. newCrawls, err := redis.Strings(c.Do("SORT", "newCrawl", "BY", "nosort")) if err != nil { return fmt.Errorf("cannot list newCrawl: %v", err) } for _, nc := range newCrawls { if nc == root || strings.HasPrefix(nc, root) && nc[len(root)] == '/' { if _, err := deleteScript.Do(c, nc); err != nil { return err } } } return nil }
[ "func", "(", "db", "*", "Database", ")", "Block", "(", "root", "string", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", ":=", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ",", "root", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove all packages under the project root.", "keys", ",", "err", ":=", "redis", ".", "Strings", "(", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "if", "key", "==", "root", "||", "strings", ".", "HasPrefix", "(", "key", ",", "root", ")", "&&", "key", "[", "len", "(", "root", ")", "]", "==", "'/'", "{", "id", ",", "err", ":=", "redis", ".", "String", "(", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ",", "key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "deleteScript", ".", "Do", "(", "c", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "db", ".", "DeleteIndex", "(", "ctx", ",", "id", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "search", ".", "ErrNoSuchDocument", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Remove all packages in the newCrawl set under the project root.", "newCrawls", ",", "err", ":=", "redis", ".", "Strings", "(", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "nc", ":=", "range", "newCrawls", "{", "if", "nc", "==", "root", "||", "strings", ".", "HasPrefix", "(", "nc", ",", "root", ")", "&&", "nc", "[", "len", "(", "root", ")", "]", "==", "'/'", "{", "if", "_", ",", "err", ":=", "deleteScript", ".", "Do", "(", "c", ",", "nc", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Block puts a domain, repo or package into the block set, removes all the // packages under it from the database and prevents future crawling from it.
[ "Block", "puts", "a", "domain", "repo", "or", "package", "into", "the", "block", "set", "removes", "all", "the", "packages", "under", "it", "from", "the", "database", "and", "prevents", "future", "crawling", "from", "it", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L773-L814
149,702
golang/gddo
database/database.go
Do
func (db *Database) Do(f func(*PackageInfo) error) error { c := db.Pool.Get() defer c.Close() cursor := 0 c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for { // Receive previous SCAN. values, err := redis.Values(c.Receive()) if err != nil { return err } var keys [][]byte if _, err := redis.Scan(values, &cursor, &keys); err != nil { return err } if cursor == 0 { break } for _, key := range keys { c.Send("HMGET", key, "gob", "score", "kind", "path", "terms", "synopis") } c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for _ = range keys { values, err := redis.Values(c.Receive()) if err != nil { return err } var ( pi PackageInfo p []byte path string terms string synopsis string ) if _, err := redis.Scan(values, &p, &pi.Score, &pi.Kind, &path, &terms, &synopsis); err != nil { return err } if p == nil { continue } pi.Size = len(path) + len(p) + len(terms) + len(synopsis) p, err = snappy.Decode(nil, p) if err != nil { return fmt.Errorf("snappy decoding %s: %v", path, err) } if err := gob.NewDecoder(bytes.NewReader(p)).Decode(&pi.PDoc); err != nil { return fmt.Errorf("gob decoding %s: %v", path, err) } if err := f(&pi); err != nil { return fmt.Errorf("func %s: %v", path, err) } } } return nil }
go
func (db *Database) Do(f func(*PackageInfo) error) error { c := db.Pool.Get() defer c.Close() cursor := 0 c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for { // Receive previous SCAN. values, err := redis.Values(c.Receive()) if err != nil { return err } var keys [][]byte if _, err := redis.Scan(values, &cursor, &keys); err != nil { return err } if cursor == 0 { break } for _, key := range keys { c.Send("HMGET", key, "gob", "score", "kind", "path", "terms", "synopis") } c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for _ = range keys { values, err := redis.Values(c.Receive()) if err != nil { return err } var ( pi PackageInfo p []byte path string terms string synopsis string ) if _, err := redis.Scan(values, &p, &pi.Score, &pi.Kind, &path, &terms, &synopsis); err != nil { return err } if p == nil { continue } pi.Size = len(path) + len(p) + len(terms) + len(synopsis) p, err = snappy.Decode(nil, p) if err != nil { return fmt.Errorf("snappy decoding %s: %v", path, err) } if err := gob.NewDecoder(bytes.NewReader(p)).Decode(&pi.PDoc); err != nil { return fmt.Errorf("gob decoding %s: %v", path, err) } if err := f(&pi); err != nil { return fmt.Errorf("func %s: %v", path, err) } } } return nil }
[ "func", "(", "db", "*", "Database", ")", "Do", "(", "f", "func", "(", "*", "PackageInfo", ")", "error", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n", "cursor", ":=", "0", "\n", "c", ".", "Send", "(", "\"", "\"", ",", "cursor", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flush", "(", ")", "\n", "for", "{", "// Receive previous SCAN.", "values", ",", "err", ":=", "redis", ".", "Values", "(", "c", ".", "Receive", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "keys", "[", "]", "[", "]", "byte", "\n", "if", "_", ",", "err", ":=", "redis", ".", "Scan", "(", "values", ",", "&", "cursor", ",", "&", "keys", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "cursor", "==", "0", "{", "break", "\n", "}", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "c", ".", "Send", "(", "\"", "\"", ",", "key", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Send", "(", "\"", "\"", ",", "cursor", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flush", "(", ")", "\n", "for", "_", "=", "range", "keys", "{", "values", ",", "err", ":=", "redis", ".", "Values", "(", "c", ".", "Receive", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "(", "pi", "PackageInfo", "\n", "p", "[", "]", "byte", "\n", "path", "string", "\n", "terms", "string", "\n", "synopsis", "string", "\n", ")", "\n\n", "if", "_", ",", "err", ":=", "redis", ".", "Scan", "(", "values", ",", "&", "p", ",", "&", "pi", ".", "Score", ",", "&", "pi", ".", "Kind", ",", "&", "path", ",", "&", "terms", ",", "&", "synopsis", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "p", "==", "nil", "{", "continue", "\n", "}", "\n\n", "pi", ".", "Size", "=", "len", "(", "path", ")", "+", "len", "(", "p", ")", "+", "len", "(", "terms", ")", "+", "len", "(", "synopsis", ")", "\n\n", "p", ",", "err", "=", "snappy", ".", "Decode", "(", "nil", ",", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "p", ")", ")", ".", "Decode", "(", "&", "pi", ".", "PDoc", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "f", "(", "&", "pi", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Do executes function f for each document in the database.
[ "Do", "executes", "function", "f", "for", "each", "document", "in", "the", "database", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L927-L989
149,703
golang/gddo
database/database.go
Reindex
func (db *Database) Reindex(ctx context.Context) error { if db.RemoteClient == nil { return errors.New("database.Reindex: no App Engine endpoint given") } c := db.Pool.Get() defer c.Close() idx, err := search.Open("packages") if err != nil { return fmt.Errorf("database: failed to open packages: %v", err) } npkgs := 0 for { // Get 200 packages from the nextCrawl set each time. Use npkgs as a cursor // to store the current position we actually indexed. Retry from the cursor // position if we received a timeout error from app engine. values, err := redis.Values(c.Do( "SORT", "nextCrawl", "LIMIT", strconv.Itoa(npkgs), "200", "GET", "pkg:*->path", "GET", "pkg:*->synopsis", "GET", "pkg:*->score", )) if err != nil { return err } if len(values) == 0 { break // all done } // The Search API should support put in batches of up to 200 documents, // the Go version of this API does not support this yet. // TODO(shantuo): Put packages in batch operations. for ; len(values) > 0; npkgs++ { var pdoc doc.Package var score float64 values, err = redis.Scan(values, &pdoc.ImportPath, &pdoc.Synopsis, &score) if err != nil { return err } // There are some corrupted data in our current database // that causes an error when putting the package into the // search index which only supports UTF8 encoding. if !utf8.ValidString(pdoc.Synopsis) { pdoc.Synopsis = "" } id, n, err := pkgIDAndImportCount(c, pdoc.ImportPath) if err != nil { return err } if _, err := idx.Put(db.RemoteClient.NewContext(ctx), id, &Package{ Path: pdoc.ImportPath, Synopsis: pdoc.Synopsis, Score: score, ImportCount: n, }); err != nil { if appengine.IsTimeoutError(err) { log.Printf("App Engine timeout: %v. Continue...", err) break } return fmt.Errorf("Failed to put index %s: %v", id, err) } } } log.Printf("%d packages are reindexed", npkgs) return nil }
go
func (db *Database) Reindex(ctx context.Context) error { if db.RemoteClient == nil { return errors.New("database.Reindex: no App Engine endpoint given") } c := db.Pool.Get() defer c.Close() idx, err := search.Open("packages") if err != nil { return fmt.Errorf("database: failed to open packages: %v", err) } npkgs := 0 for { // Get 200 packages from the nextCrawl set each time. Use npkgs as a cursor // to store the current position we actually indexed. Retry from the cursor // position if we received a timeout error from app engine. values, err := redis.Values(c.Do( "SORT", "nextCrawl", "LIMIT", strconv.Itoa(npkgs), "200", "GET", "pkg:*->path", "GET", "pkg:*->synopsis", "GET", "pkg:*->score", )) if err != nil { return err } if len(values) == 0 { break // all done } // The Search API should support put in batches of up to 200 documents, // the Go version of this API does not support this yet. // TODO(shantuo): Put packages in batch operations. for ; len(values) > 0; npkgs++ { var pdoc doc.Package var score float64 values, err = redis.Scan(values, &pdoc.ImportPath, &pdoc.Synopsis, &score) if err != nil { return err } // There are some corrupted data in our current database // that causes an error when putting the package into the // search index which only supports UTF8 encoding. if !utf8.ValidString(pdoc.Synopsis) { pdoc.Synopsis = "" } id, n, err := pkgIDAndImportCount(c, pdoc.ImportPath) if err != nil { return err } if _, err := idx.Put(db.RemoteClient.NewContext(ctx), id, &Package{ Path: pdoc.ImportPath, Synopsis: pdoc.Synopsis, Score: score, ImportCount: n, }); err != nil { if appengine.IsTimeoutError(err) { log.Printf("App Engine timeout: %v. Continue...", err) break } return fmt.Errorf("Failed to put index %s: %v", id, err) } } } log.Printf("%d packages are reindexed", npkgs) return nil }
[ "func", "(", "db", "*", "Database", ")", "Reindex", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "db", ".", "RemoteClient", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "idx", ",", "err", ":=", "search", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "npkgs", ":=", "0", "\n", "for", "{", "// Get 200 packages from the nextCrawl set each time. Use npkgs as a cursor", "// to store the current position we actually indexed. Retry from the cursor", "// position if we received a timeout error from app engine.", "values", ",", "err", ":=", "redis", ".", "Values", "(", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "npkgs", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "values", ")", "==", "0", "{", "break", "// all done", "\n", "}", "\n\n", "// The Search API should support put in batches of up to 200 documents,", "// the Go version of this API does not support this yet.", "// TODO(shantuo): Put packages in batch operations.", "for", ";", "len", "(", "values", ")", ">", "0", ";", "npkgs", "++", "{", "var", "pdoc", "doc", ".", "Package", "\n", "var", "score", "float64", "\n", "values", ",", "err", "=", "redis", ".", "Scan", "(", "values", ",", "&", "pdoc", ".", "ImportPath", ",", "&", "pdoc", ".", "Synopsis", ",", "&", "score", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// There are some corrupted data in our current database", "// that causes an error when putting the package into the", "// search index which only supports UTF8 encoding.", "if", "!", "utf8", ".", "ValidString", "(", "pdoc", ".", "Synopsis", ")", "{", "pdoc", ".", "Synopsis", "=", "\"", "\"", "\n", "}", "\n", "id", ",", "n", ",", "err", ":=", "pkgIDAndImportCount", "(", "c", ",", "pdoc", ".", "ImportPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "idx", ".", "Put", "(", "db", ".", "RemoteClient", ".", "NewContext", "(", "ctx", ")", ",", "id", ",", "&", "Package", "{", "Path", ":", "pdoc", ".", "ImportPath", ",", "Synopsis", ":", "pdoc", ".", "Synopsis", ",", "Score", ":", "score", ",", "ImportCount", ":", "n", ",", "}", ")", ";", "err", "!=", "nil", "{", "if", "appengine", ".", "IsTimeoutError", "(", "err", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "break", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "npkgs", ")", "\n", "return", "nil", "\n", "}" ]
// Reindex gets all the packages in database and put them into the search index. // This will update the search index with the path, synopsis, score, import counts // of all the packages in the database.
[ "Reindex", "gets", "all", "the", "packages", "in", "database", "and", "put", "them", "into", "the", "search", "index", ".", "This", "will", "update", "the", "search", "index", "with", "the", "path", "synopsis", "score", "import", "counts", "of", "all", "the", "packages", "in", "the", "database", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L1238-L1305
149,704
golang/gddo
database/database.go
PutIndex
func (db *Database) PutIndex(ctx context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if db.RemoteClient == nil { return nil } return putIndex(db.RemoteClient.NewContext(ctx), pdoc, id, score, importCount) }
go
func (db *Database) PutIndex(ctx context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if db.RemoteClient == nil { return nil } return putIndex(db.RemoteClient.NewContext(ctx), pdoc, id, score, importCount) }
[ "func", "(", "db", "*", "Database", ")", "PutIndex", "(", "ctx", "context", ".", "Context", ",", "pdoc", "*", "doc", ".", "Package", ",", "id", "string", ",", "score", "float64", ",", "importCount", "int", ")", "error", "{", "if", "db", ".", "RemoteClient", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "putIndex", "(", "db", ".", "RemoteClient", ".", "NewContext", "(", "ctx", ")", ",", "pdoc", ",", "id", ",", "score", ",", "importCount", ")", "\n", "}" ]
// PutIndex puts a package into App Engine search index. ID is the package ID in the database. // It is no-op when running locally without setting up remote_api.
[ "PutIndex", "puts", "a", "package", "into", "App", "Engine", "search", "index", ".", "ID", "is", "the", "package", "ID", "in", "the", "database", ".", "It", "is", "no", "-", "op", "when", "running", "locally", "without", "setting", "up", "remote_api", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L1316-L1321
149,705
golang/gddo
database/database.go
DeleteIndex
func (db *Database) DeleteIndex(ctx context.Context, id string) error { if db.RemoteClient == nil { return nil } return deleteIndex(db.RemoteClient.NewContext(ctx), id) }
go
func (db *Database) DeleteIndex(ctx context.Context, id string) error { if db.RemoteClient == nil { return nil } return deleteIndex(db.RemoteClient.NewContext(ctx), id) }
[ "func", "(", "db", "*", "Database", ")", "DeleteIndex", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "if", "db", ".", "RemoteClient", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "deleteIndex", "(", "db", ".", "RemoteClient", ".", "NewContext", "(", "ctx", ")", ",", "id", ")", "\n", "}" ]
// DeleteIndex deletes a package from App Engine search index. ID is the package ID in the database. // It is no-op when running locally without setting up remote_api.
[ "DeleteIndex", "deletes", "a", "package", "from", "App", "Engine", "search", "index", ".", "ID", "is", "the", "package", "ID", "in", "the", "database", ".", "It", "is", "no", "-", "op", "when", "running", "locally", "without", "setting", "up", "remote_api", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L1325-L1330
149,706
golang/gddo
gosrc/gosrc.go
GetPresentation
func GetPresentation(ctx context.Context, client *http.Client, importPath string) (*Presentation, error) { ext := path.Ext(importPath) if ext != ".slide" && ext != ".article" { return nil, NotFoundError{Message: "unknown file extension."} } importPath, file := path.Split(importPath) importPath = strings.TrimSuffix(importPath, "/") for _, s := range services { if s.getPresentation == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { match["file"] = file return s.getPresentation(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
go
func GetPresentation(ctx context.Context, client *http.Client, importPath string) (*Presentation, error) { ext := path.Ext(importPath) if ext != ".slide" && ext != ".article" { return nil, NotFoundError{Message: "unknown file extension."} } importPath, file := path.Split(importPath) importPath = strings.TrimSuffix(importPath, "/") for _, s := range services { if s.getPresentation == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { match["file"] = file return s.getPresentation(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
[ "func", "GetPresentation", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ",", "importPath", "string", ")", "(", "*", "Presentation", ",", "error", ")", "{", "ext", ":=", "path", ".", "Ext", "(", "importPath", ")", "\n", "if", "ext", "!=", "\"", "\"", "&&", "ext", "!=", "\"", "\"", "{", "return", "nil", ",", "NotFoundError", "{", "Message", ":", "\"", "\"", "}", "\n", "}", "\n\n", "importPath", ",", "file", ":=", "path", ".", "Split", "(", "importPath", ")", "\n", "importPath", "=", "strings", ".", "TrimSuffix", "(", "importPath", ",", "\"", "\"", ")", "\n", "for", "_", ",", "s", ":=", "range", "services", "{", "if", "s", ".", "getPresentation", "==", "nil", "{", "continue", "\n", "}", "\n", "match", ",", "err", ":=", "s", ".", "match", "(", "importPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "match", "!=", "nil", "{", "match", "[", "\"", "\"", "]", "=", "file", "\n", "return", "s", ".", "getPresentation", "(", "ctx", ",", "client", ",", "match", ")", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "NotFoundError", "{", "Message", ":", "\"", "\"", "}", "\n", "}" ]
// GetPresentation gets a presentation from the the given path.
[ "GetPresentation", "gets", "a", "presentation", "from", "the", "the", "given", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/gosrc.go#L503-L525
149,707
golang/gddo
gosrc/gosrc.go
GetProject
func GetProject(ctx context.Context, client *http.Client, importPath string) (*Project, error) { for _, s := range services { if s.getProject == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { return s.getProject(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
go
func GetProject(ctx context.Context, client *http.Client, importPath string) (*Project, error) { for _, s := range services { if s.getProject == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { return s.getProject(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
[ "func", "GetProject", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ",", "importPath", "string", ")", "(", "*", "Project", ",", "error", ")", "{", "for", "_", ",", "s", ":=", "range", "services", "{", "if", "s", ".", "getProject", "==", "nil", "{", "continue", "\n", "}", "\n", "match", ",", "err", ":=", "s", ".", "match", "(", "importPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "match", "!=", "nil", "{", "return", "s", ".", "getProject", "(", "ctx", ",", "client", ",", "match", ")", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "NotFoundError", "{", "Message", ":", "\"", "\"", "}", "\n", "}" ]
// GetProject gets information about a repository.
[ "GetProject", "gets", "information", "about", "a", "repository", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/gosrc.go#L528-L542
149,708
golang/gddo
gosrc/gosrc.go
MaybeRedirect
func MaybeRedirect(importPath, importComment, resolvedGitHubPath string) error { switch { case importComment != "": // Redirect to import comment, if not already there. if importPath != importComment { return NotFoundError{ Message: "not at canonical import path", Redirect: importComment, } } // Redirect to GitHub's reported canonical casing when there's no import comment, // and the import path differs from resolved GitHub path only in case. case importComment == "" && resolvedGitHubPath != "" && strings.EqualFold(importPath, resolvedGitHubPath): // Redirect to resolved GitHub path, if not already there. if importPath != resolvedGitHubPath { return NotFoundError{ Message: "not at canonical import path", Redirect: resolvedGitHubPath, } } } // No redirect. return nil }
go
func MaybeRedirect(importPath, importComment, resolvedGitHubPath string) error { switch { case importComment != "": // Redirect to import comment, if not already there. if importPath != importComment { return NotFoundError{ Message: "not at canonical import path", Redirect: importComment, } } // Redirect to GitHub's reported canonical casing when there's no import comment, // and the import path differs from resolved GitHub path only in case. case importComment == "" && resolvedGitHubPath != "" && strings.EqualFold(importPath, resolvedGitHubPath): // Redirect to resolved GitHub path, if not already there. if importPath != resolvedGitHubPath { return NotFoundError{ Message: "not at canonical import path", Redirect: resolvedGitHubPath, } } } // No redirect. return nil }
[ "func", "MaybeRedirect", "(", "importPath", ",", "importComment", ",", "resolvedGitHubPath", "string", ")", "error", "{", "switch", "{", "case", "importComment", "!=", "\"", "\"", ":", "// Redirect to import comment, if not already there.", "if", "importPath", "!=", "importComment", "{", "return", "NotFoundError", "{", "Message", ":", "\"", "\"", ",", "Redirect", ":", "importComment", ",", "}", "\n", "}", "\n\n", "// Redirect to GitHub's reported canonical casing when there's no import comment,", "// and the import path differs from resolved GitHub path only in case.", "case", "importComment", "==", "\"", "\"", "&&", "resolvedGitHubPath", "!=", "\"", "\"", "&&", "strings", ".", "EqualFold", "(", "importPath", ",", "resolvedGitHubPath", ")", ":", "// Redirect to resolved GitHub path, if not already there.", "if", "importPath", "!=", "resolvedGitHubPath", "{", "return", "NotFoundError", "{", "Message", ":", "\"", "\"", ",", "Redirect", ":", "resolvedGitHubPath", ",", "}", "\n", "}", "\n", "}", "\n\n", "// No redirect.", "return", "nil", "\n", "}" ]
// MaybeRedirect uses the provided import path, import comment, and resolved GitHub path // to make a decision of whether to redirect to another, more canonical import path. // It returns nil error to indicate no redirect, or a NotFoundError error to redirect.
[ "MaybeRedirect", "uses", "the", "provided", "import", "path", "import", "comment", "and", "resolved", "GitHub", "path", "to", "make", "a", "decision", "of", "whether", "to", "redirect", "to", "another", "more", "canonical", "import", "path", ".", "It", "returns", "nil", "error", "to", "indicate", "no", "redirect", "or", "a", "NotFoundError", "error", "to", "redirect", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/gosrc.go#L547-L574
149,709
golang/gddo
gosrc/build.go
Import
func (dir *Directory) Import(ctx *build.Context, mode build.ImportMode) (*build.Package, error) { safeCopy := *ctx ctx = &safeCopy ctx.JoinPath = path.Join ctx.IsAbsPath = path.IsAbs ctx.SplitPathList = func(list string) []string { return strings.Split(list, ":") } ctx.IsDir = func(path string) bool { return path == "." } ctx.HasSubdir = func(root, dir string) (rel string, ok bool) { return "", false } ctx.ReadDir = dir.readDir ctx.OpenFile = dir.openFile return ctx.ImportDir(".", mode) }
go
func (dir *Directory) Import(ctx *build.Context, mode build.ImportMode) (*build.Package, error) { safeCopy := *ctx ctx = &safeCopy ctx.JoinPath = path.Join ctx.IsAbsPath = path.IsAbs ctx.SplitPathList = func(list string) []string { return strings.Split(list, ":") } ctx.IsDir = func(path string) bool { return path == "." } ctx.HasSubdir = func(root, dir string) (rel string, ok bool) { return "", false } ctx.ReadDir = dir.readDir ctx.OpenFile = dir.openFile return ctx.ImportDir(".", mode) }
[ "func", "(", "dir", "*", "Directory", ")", "Import", "(", "ctx", "*", "build", ".", "Context", ",", "mode", "build", ".", "ImportMode", ")", "(", "*", "build", ".", "Package", ",", "error", ")", "{", "safeCopy", ":=", "*", "ctx", "\n", "ctx", "=", "&", "safeCopy", "\n", "ctx", ".", "JoinPath", "=", "path", ".", "Join", "\n", "ctx", ".", "IsAbsPath", "=", "path", ".", "IsAbs", "\n", "ctx", ".", "SplitPathList", "=", "func", "(", "list", "string", ")", "[", "]", "string", "{", "return", "strings", ".", "Split", "(", "list", ",", "\"", "\"", ")", "}", "\n", "ctx", ".", "IsDir", "=", "func", "(", "path", "string", ")", "bool", "{", "return", "path", "==", "\"", "\"", "}", "\n", "ctx", ".", "HasSubdir", "=", "func", "(", "root", ",", "dir", "string", ")", "(", "rel", "string", ",", "ok", "bool", ")", "{", "return", "\"", "\"", ",", "false", "}", "\n", "ctx", ".", "ReadDir", "=", "dir", ".", "readDir", "\n", "ctx", ".", "OpenFile", "=", "dir", ".", "openFile", "\n", "return", "ctx", ".", "ImportDir", "(", "\"", "\"", ",", "mode", ")", "\n", "}" ]
// Import returns details about the package in the directory.
[ "Import", "returns", "details", "about", "the", "package", "in", "the", "directory", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/build.go#L21-L32
149,710
golang/gddo
gddo-server/template.go
getFlashMessages
func getFlashMessages(resp http.ResponseWriter, req *http.Request) []flashMessage { c, err := req.Cookie("flash") if err == http.ErrNoCookie { return nil } http.SetCookie(resp, &http.Cookie{Name: "flash", Path: "/", MaxAge: -1, Expires: time.Now().Add(-100 * 24 * time.Hour)}) if err != nil { return nil } p, err := base64.URLEncoding.DecodeString(c.Value) if err != nil { return nil } var messages []flashMessage for _, s := range strings.Split(string(p), "\000") { idArgs := strings.Split(s, "\001") messages = append(messages, flashMessage{ID: idArgs[0], Args: idArgs[1:]}) } return messages }
go
func getFlashMessages(resp http.ResponseWriter, req *http.Request) []flashMessage { c, err := req.Cookie("flash") if err == http.ErrNoCookie { return nil } http.SetCookie(resp, &http.Cookie{Name: "flash", Path: "/", MaxAge: -1, Expires: time.Now().Add(-100 * 24 * time.Hour)}) if err != nil { return nil } p, err := base64.URLEncoding.DecodeString(c.Value) if err != nil { return nil } var messages []flashMessage for _, s := range strings.Split(string(p), "\000") { idArgs := strings.Split(s, "\001") messages = append(messages, flashMessage{ID: idArgs[0], Args: idArgs[1:]}) } return messages }
[ "func", "getFlashMessages", "(", "resp", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "[", "]", "flashMessage", "{", "c", ",", "err", ":=", "req", ".", "Cookie", "(", "\"", "\"", ")", "\n", "if", "err", "==", "http", ".", "ErrNoCookie", "{", "return", "nil", "\n", "}", "\n", "http", ".", "SetCookie", "(", "resp", ",", "&", "http", ".", "Cookie", "{", "Name", ":", "\"", "\"", ",", "Path", ":", "\"", "\"", ",", "MaxAge", ":", "-", "1", ",", "Expires", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "100", "*", "24", "*", "time", ".", "Hour", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "p", ",", "err", ":=", "base64", ".", "URLEncoding", ".", "DecodeString", "(", "c", ".", "Value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "var", "messages", "[", "]", "flashMessage", "\n", "for", "_", ",", "s", ":=", "range", "strings", ".", "Split", "(", "string", "(", "p", ")", ",", "\"", "\\000", "\"", ")", "{", "idArgs", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\\001", "\"", ")", "\n", "messages", "=", "append", "(", "messages", ",", "flashMessage", "{", "ID", ":", "idArgs", "[", "0", "]", ",", "Args", ":", "idArgs", "[", "1", ":", "]", "}", ")", "\n", "}", "\n", "return", "messages", "\n", "}" ]
// getFlashMessages retrieves flash messages from the request and clears the flash cookie if needed.
[ "getFlashMessages", "retrieves", "flash", "messages", "from", "the", "request", "and", "clears", "the", "flash", "cookie", "if", "needed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L41-L60
149,711
golang/gddo
gddo-server/template.go
setFlashMessages
func setFlashMessages(resp http.ResponseWriter, messages []flashMessage) { var buf []byte for i, message := range messages { if i > 0 { buf = append(buf, '\000') } buf = append(buf, message.ID...) for _, arg := range message.Args { buf = append(buf, '\001') buf = append(buf, arg...) } } value := base64.URLEncoding.EncodeToString(buf) http.SetCookie(resp, &http.Cookie{Name: "flash", Value: value, Path: "/"}) }
go
func setFlashMessages(resp http.ResponseWriter, messages []flashMessage) { var buf []byte for i, message := range messages { if i > 0 { buf = append(buf, '\000') } buf = append(buf, message.ID...) for _, arg := range message.Args { buf = append(buf, '\001') buf = append(buf, arg...) } } value := base64.URLEncoding.EncodeToString(buf) http.SetCookie(resp, &http.Cookie{Name: "flash", Value: value, Path: "/"}) }
[ "func", "setFlashMessages", "(", "resp", "http", ".", "ResponseWriter", ",", "messages", "[", "]", "flashMessage", ")", "{", "var", "buf", "[", "]", "byte", "\n", "for", "i", ",", "message", ":=", "range", "messages", "{", "if", "i", ">", "0", "{", "buf", "=", "append", "(", "buf", ",", "'\\000'", ")", "\n", "}", "\n", "buf", "=", "append", "(", "buf", ",", "message", ".", "ID", "...", ")", "\n", "for", "_", ",", "arg", ":=", "range", "message", ".", "Args", "{", "buf", "=", "append", "(", "buf", ",", "'\\001'", ")", "\n", "buf", "=", "append", "(", "buf", ",", "arg", "...", ")", "\n", "}", "\n", "}", "\n", "value", ":=", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "buf", ")", "\n", "http", ".", "SetCookie", "(", "resp", ",", "&", "http", ".", "Cookie", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "value", ",", "Path", ":", "\"", "\"", "}", ")", "\n", "}" ]
// setFlashMessages sets a cookie with the given flash messages.
[ "setFlashMessages", "sets", "a", "cookie", "with", "the", "given", "flash", "messages", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L63-L77
149,712
golang/gddo
gddo-server/template.go
UsesLink
func (pdoc *tdoc) UsesLink(title string, defParts ...string) htemp.HTML { if pdoc.sourcegraphURL == "" { return "" } var def string switch len(defParts) { case 1: // Funcs and types have one def part. def = defParts[0] case 3: // Methods have three def parts, the original receiver name, actual receiver name and method name. orig, recv, methodName := defParts[0], defParts[1], defParts[2] if orig == "" { // TODO: Remove this fallback after 2016-08-05. It's only needed temporarily to backfill data. // Actual receiver is not needed, it's only used because original receiver value // was recently added to gddo/doc package and will be blank until next package rebuild. // // Use actual receiver as fallback. orig = recv } // Trim "*" from "*T" if it's a pointer receiver method. typeName := strings.TrimPrefix(orig, "*") def = typeName + "/" + methodName default: panic(fmt.Errorf("%v defParts, want 1 or 3", len(defParts))) } q := url.Values{ "repo": {pdoc.ProjectRoot}, "pkg": {pdoc.ImportPath}, "def": {def}, } u := pdoc.sourcegraphURL + "/-/godoc/refs?" + q.Encode() return htemp.HTML(fmt.Sprintf(`<a class="uses" title="%s" href="%s">Uses</a>`, htemp.HTMLEscapeString(title), htemp.HTMLEscapeString(u))) }
go
func (pdoc *tdoc) UsesLink(title string, defParts ...string) htemp.HTML { if pdoc.sourcegraphURL == "" { return "" } var def string switch len(defParts) { case 1: // Funcs and types have one def part. def = defParts[0] case 3: // Methods have three def parts, the original receiver name, actual receiver name and method name. orig, recv, methodName := defParts[0], defParts[1], defParts[2] if orig == "" { // TODO: Remove this fallback after 2016-08-05. It's only needed temporarily to backfill data. // Actual receiver is not needed, it's only used because original receiver value // was recently added to gddo/doc package and will be blank until next package rebuild. // // Use actual receiver as fallback. orig = recv } // Trim "*" from "*T" if it's a pointer receiver method. typeName := strings.TrimPrefix(orig, "*") def = typeName + "/" + methodName default: panic(fmt.Errorf("%v defParts, want 1 or 3", len(defParts))) } q := url.Values{ "repo": {pdoc.ProjectRoot}, "pkg": {pdoc.ImportPath}, "def": {def}, } u := pdoc.sourcegraphURL + "/-/godoc/refs?" + q.Encode() return htemp.HTML(fmt.Sprintf(`<a class="uses" title="%s" href="%s">Uses</a>`, htemp.HTMLEscapeString(title), htemp.HTMLEscapeString(u))) }
[ "func", "(", "pdoc", "*", "tdoc", ")", "UsesLink", "(", "title", "string", ",", "defParts", "...", "string", ")", "htemp", ".", "HTML", "{", "if", "pdoc", ".", "sourcegraphURL", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", "def", "string", "\n", "switch", "len", "(", "defParts", ")", "{", "case", "1", ":", "// Funcs and types have one def part.", "def", "=", "defParts", "[", "0", "]", "\n\n", "case", "3", ":", "// Methods have three def parts, the original receiver name, actual receiver name and method name.", "orig", ",", "recv", ",", "methodName", ":=", "defParts", "[", "0", "]", ",", "defParts", "[", "1", "]", ",", "defParts", "[", "2", "]", "\n\n", "if", "orig", "==", "\"", "\"", "{", "// TODO: Remove this fallback after 2016-08-05. It's only needed temporarily to backfill data.", "// Actual receiver is not needed, it's only used because original receiver value", "// was recently added to gddo/doc package and will be blank until next package rebuild.", "//", "// Use actual receiver as fallback.", "orig", "=", "recv", "\n", "}", "\n\n", "// Trim \"*\" from \"*T\" if it's a pointer receiver method.", "typeName", ":=", "strings", ".", "TrimPrefix", "(", "orig", ",", "\"", "\"", ")", "\n\n", "def", "=", "typeName", "+", "\"", "\"", "+", "methodName", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "defParts", ")", ")", ")", "\n", "}", "\n\n", "q", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "pdoc", ".", "ProjectRoot", "}", ",", "\"", "\"", ":", "{", "pdoc", ".", "ImportPath", "}", ",", "\"", "\"", ":", "{", "def", "}", ",", "}", "\n", "u", ":=", "pdoc", ".", "sourcegraphURL", "+", "\"", "\"", "+", "q", ".", "Encode", "(", ")", "\n", "return", "htemp", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "`<a class=\"uses\" title=\"%s\" href=\"%s\">Uses</a>`", ",", "htemp", ".", "HTMLEscapeString", "(", "title", ")", ",", "htemp", ".", "HTMLEscapeString", "(", "u", ")", ")", ")", "\n", "}" ]
// UsesLink generates a link to uses of a symbol definition. // title is used as the tooltip. defParts are parts of the symbol definition name.
[ "UsesLink", "generates", "a", "link", "to", "uses", "of", "a", "symbol", "definition", ".", "title", "is", "used", "as", "the", "tooltip", ".", "defParts", "are", "parts", "of", "the", "symbol", "definition", "name", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L114-L153
149,713
golang/gddo
gddo-server/template.go
relativePathFn
func relativePathFn(path string, parentPath interface{}) string { if p, ok := parentPath.(string); ok && p != "" && strings.HasPrefix(path, p) { path = path[len(p)+1:] } return path }
go
func relativePathFn(path string, parentPath interface{}) string { if p, ok := parentPath.(string); ok && p != "" && strings.HasPrefix(path, p) { path = path[len(p)+1:] } return path }
[ "func", "relativePathFn", "(", "path", "string", ",", "parentPath", "interface", "{", "}", ")", "string", "{", "if", "p", ",", "ok", ":=", "parentPath", ".", "(", "string", ")", ";", "ok", "&&", "p", "!=", "\"", "\"", "&&", "strings", ".", "HasPrefix", "(", "path", ",", "p", ")", "{", "path", "=", "path", "[", "len", "(", "p", ")", "+", "1", ":", "]", "\n", "}", "\n", "return", "path", "\n", "}" ]
// relativePathFn formats an import path as HTML.
[ "relativePathFn", "formats", "an", "import", "path", "as", "HTML", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L321-L326
149,714
golang/gddo
gddo-server/template.go
importPathFn
func importPathFn(path string) htemp.HTML { path = htemp.HTMLEscapeString(path) if len(path) > 45 { // Allow long import paths to break following "/" path = strings.Replace(path, "/", "/&#8203;", -1) } return htemp.HTML(path) }
go
func importPathFn(path string) htemp.HTML { path = htemp.HTMLEscapeString(path) if len(path) > 45 { // Allow long import paths to break following "/" path = strings.Replace(path, "/", "/&#8203;", -1) } return htemp.HTML(path) }
[ "func", "importPathFn", "(", "path", "string", ")", "htemp", ".", "HTML", "{", "path", "=", "htemp", ".", "HTMLEscapeString", "(", "path", ")", "\n", "if", "len", "(", "path", ")", ">", "45", "{", "// Allow long import paths to break following \"/\"", "path", "=", "strings", ".", "Replace", "(", "path", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}", "\n", "return", "htemp", ".", "HTML", "(", "path", ")", "\n", "}" ]
// importPathFn formats an import with zero width space characters to allow for breaks.
[ "importPathFn", "formats", "an", "import", "with", "zero", "width", "space", "characters", "to", "allow", "for", "breaks", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L329-L336
149,715
golang/gddo
gddo-server/template.go
commentFn
func commentFn(v string) htemp.HTML { var buf bytes.Buffer godoc.ToHTML(&buf, v, nil) p := buf.Bytes() p = replaceAll(p, h3Pat, func(out, src []byte, m []int) []byte { out = append(out, `<h4 id="`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">`...) out = append(out, src[m[4]:m[5]]...) out = append(out, ` <a class="permalink" href="#`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">&para</a></h4>`...) return out }) p = replaceAll(p, rfcPat, func(out, src []byte, m []int) []byte { out = append(out, `<a href="http://tools.ietf.org/html/rfc`...) out = append(out, src[m[2]:m[3]]...) // If available, add section fragment if m[4] != -1 { out = append(out, `#section-`...) out = append(out, src[m[6]:m[7]]...) } out = append(out, `">`...) out = append(out, src[m[0]:m[1]]...) out = append(out, `</a>`...) return out }) p = replaceAll(p, packagePat, func(out, src []byte, m []int) []byte { path := bytes.TrimRight(src[m[2]:m[3]], ".!?:") if !gosrc.IsValidPath(string(path)) { return append(out, src[m[0]:m[1]]...) } out = append(out, src[m[0]:m[2]]...) out = append(out, `<a href="/`...) out = append(out, path...) out = append(out, `">`...) out = append(out, path...) out = append(out, `</a>`...) out = append(out, src[m[2]+len(path):m[1]]...) return out }) return htemp.HTML(p) }
go
func commentFn(v string) htemp.HTML { var buf bytes.Buffer godoc.ToHTML(&buf, v, nil) p := buf.Bytes() p = replaceAll(p, h3Pat, func(out, src []byte, m []int) []byte { out = append(out, `<h4 id="`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">`...) out = append(out, src[m[4]:m[5]]...) out = append(out, ` <a class="permalink" href="#`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">&para</a></h4>`...) return out }) p = replaceAll(p, rfcPat, func(out, src []byte, m []int) []byte { out = append(out, `<a href="http://tools.ietf.org/html/rfc`...) out = append(out, src[m[2]:m[3]]...) // If available, add section fragment if m[4] != -1 { out = append(out, `#section-`...) out = append(out, src[m[6]:m[7]]...) } out = append(out, `">`...) out = append(out, src[m[0]:m[1]]...) out = append(out, `</a>`...) return out }) p = replaceAll(p, packagePat, func(out, src []byte, m []int) []byte { path := bytes.TrimRight(src[m[2]:m[3]], ".!?:") if !gosrc.IsValidPath(string(path)) { return append(out, src[m[0]:m[1]]...) } out = append(out, src[m[0]:m[2]]...) out = append(out, `<a href="/`...) out = append(out, path...) out = append(out, `">`...) out = append(out, path...) out = append(out, `</a>`...) out = append(out, src[m[2]+len(path):m[1]]...) return out }) return htemp.HTML(p) }
[ "func", "commentFn", "(", "v", "string", ")", "htemp", ".", "HTML", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "godoc", ".", "ToHTML", "(", "&", "buf", ",", "v", ",", "nil", ")", "\n", "p", ":=", "buf", ".", "Bytes", "(", ")", "\n", "p", "=", "replaceAll", "(", "p", ",", "h3Pat", ",", "func", "(", "out", ",", "src", "[", "]", "byte", ",", "m", "[", "]", "int", ")", "[", "]", "byte", "{", "out", "=", "append", "(", "out", ",", "`<h4 id=\"`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "2", "]", ":", "m", "[", "3", "]", "]", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "`\">`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "4", "]", ":", "m", "[", "5", "]", "]", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "` <a class=\"permalink\" href=\"#`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "2", "]", ":", "m", "[", "3", "]", "]", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "`\">&para</a></h4>`", "...", ")", "\n", "return", "out", "\n", "}", ")", "\n", "p", "=", "replaceAll", "(", "p", ",", "rfcPat", ",", "func", "(", "out", ",", "src", "[", "]", "byte", ",", "m", "[", "]", "int", ")", "[", "]", "byte", "{", "out", "=", "append", "(", "out", ",", "`<a href=\"http://tools.ietf.org/html/rfc`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "2", "]", ":", "m", "[", "3", "]", "]", "...", ")", "\n\n", "// If available, add section fragment", "if", "m", "[", "4", "]", "!=", "-", "1", "{", "out", "=", "append", "(", "out", ",", "`#section-`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "6", "]", ":", "m", "[", "7", "]", "]", "...", ")", "\n", "}", "\n\n", "out", "=", "append", "(", "out", ",", "`\">`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "0", "]", ":", "m", "[", "1", "]", "]", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "`</a>`", "...", ")", "\n", "return", "out", "\n", "}", ")", "\n", "p", "=", "replaceAll", "(", "p", ",", "packagePat", ",", "func", "(", "out", ",", "src", "[", "]", "byte", ",", "m", "[", "]", "int", ")", "[", "]", "byte", "{", "path", ":=", "bytes", ".", "TrimRight", "(", "src", "[", "m", "[", "2", "]", ":", "m", "[", "3", "]", "]", ",", "\"", "\"", ")", "\n", "if", "!", "gosrc", ".", "IsValidPath", "(", "string", "(", "path", ")", ")", "{", "return", "append", "(", "out", ",", "src", "[", "m", "[", "0", "]", ":", "m", "[", "1", "]", "]", "...", ")", "\n", "}", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "0", "]", ":", "m", "[", "2", "]", "]", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "`<a href=\"/`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "path", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "`\">`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "path", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "`</a>`", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "src", "[", "m", "[", "2", "]", "+", "len", "(", "path", ")", ":", "m", "[", "1", "]", "]", "...", ")", "\n", "return", "out", "\n", "}", ")", "\n", "return", "htemp", ".", "HTML", "(", "p", ")", "\n", "}" ]
// commentFn formats a source code comment as HTML.
[ "commentFn", "formats", "a", "source", "code", "comment", "as", "HTML", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L362-L406
149,716
golang/gddo
gddo-server/template.go
commentTextFn
func commentTextFn(v string) string { const indent = " " var buf bytes.Buffer godoc.ToText(&buf, v, indent, "\t", 80-2*len(indent)) p := buf.Bytes() return string(p) }
go
func commentTextFn(v string) string { const indent = " " var buf bytes.Buffer godoc.ToText(&buf, v, indent, "\t", 80-2*len(indent)) p := buf.Bytes() return string(p) }
[ "func", "commentTextFn", "(", "v", "string", ")", "string", "{", "const", "indent", "=", "\"", "\"", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "godoc", ".", "ToText", "(", "&", "buf", ",", "v", ",", "indent", ",", "\"", "\\t", "\"", ",", "80", "-", "2", "*", "len", "(", "indent", ")", ")", "\n", "p", ":=", "buf", ".", "Bytes", "(", ")", "\n", "return", "string", "(", "p", ")", "\n", "}" ]
// commentTextFn formats a source code comment as text.
[ "commentTextFn", "formats", "a", "source", "code", "comment", "as", "text", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L409-L415
149,717
golang/gddo
httputil/transport.go
RoundTrip
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { var reqCopy *http.Request if t.UserAgent != "" { reqCopy = copyRequest(req) reqCopy.Header.Set("User-Agent", t.UserAgent) } if req.URL.Host == "api.github.com" && req.URL.Scheme == "https" { switch { case t.GithubClientID != "" && t.GithubClientSecret != "": if reqCopy == nil { reqCopy = copyRequest(req) } if reqCopy.URL.RawQuery == "" { reqCopy.URL.RawQuery = "client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } else { reqCopy.URL.RawQuery += "&client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } case t.GithubToken != "": if reqCopy == nil { reqCopy = copyRequest(req) } reqCopy.Header.Set("Authorization", "token "+t.GithubToken) } } if reqCopy != nil { return t.base().RoundTrip(reqCopy) } return t.base().RoundTrip(req) }
go
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { var reqCopy *http.Request if t.UserAgent != "" { reqCopy = copyRequest(req) reqCopy.Header.Set("User-Agent", t.UserAgent) } if req.URL.Host == "api.github.com" && req.URL.Scheme == "https" { switch { case t.GithubClientID != "" && t.GithubClientSecret != "": if reqCopy == nil { reqCopy = copyRequest(req) } if reqCopy.URL.RawQuery == "" { reqCopy.URL.RawQuery = "client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } else { reqCopy.URL.RawQuery += "&client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } case t.GithubToken != "": if reqCopy == nil { reqCopy = copyRequest(req) } reqCopy.Header.Set("Authorization", "token "+t.GithubToken) } } if reqCopy != nil { return t.base().RoundTrip(reqCopy) } return t.base().RoundTrip(req) }
[ "func", "(", "t", "*", "AuthTransport", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "var", "reqCopy", "*", "http", ".", "Request", "\n", "if", "t", ".", "UserAgent", "!=", "\"", "\"", "{", "reqCopy", "=", "copyRequest", "(", "req", ")", "\n", "reqCopy", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "t", ".", "UserAgent", ")", "\n", "}", "\n", "if", "req", ".", "URL", ".", "Host", "==", "\"", "\"", "&&", "req", ".", "URL", ".", "Scheme", "==", "\"", "\"", "{", "switch", "{", "case", "t", ".", "GithubClientID", "!=", "\"", "\"", "&&", "t", ".", "GithubClientSecret", "!=", "\"", "\"", ":", "if", "reqCopy", "==", "nil", "{", "reqCopy", "=", "copyRequest", "(", "req", ")", "\n", "}", "\n", "if", "reqCopy", ".", "URL", ".", "RawQuery", "==", "\"", "\"", "{", "reqCopy", ".", "URL", ".", "RawQuery", "=", "\"", "\"", "+", "t", ".", "GithubClientID", "+", "\"", "\"", "+", "t", ".", "GithubClientSecret", "\n", "}", "else", "{", "reqCopy", ".", "URL", ".", "RawQuery", "+=", "\"", "\"", "+", "t", ".", "GithubClientID", "+", "\"", "\"", "+", "t", ".", "GithubClientSecret", "\n", "}", "\n", "case", "t", ".", "GithubToken", "!=", "\"", "\"", ":", "if", "reqCopy", "==", "nil", "{", "reqCopy", "=", "copyRequest", "(", "req", ")", "\n", "}", "\n", "reqCopy", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", "+", "t", ".", "GithubToken", ")", "\n", "}", "\n", "}", "\n", "if", "reqCopy", "!=", "nil", "{", "return", "t", ".", "base", "(", ")", ".", "RoundTrip", "(", "reqCopy", ")", "\n", "}", "\n", "return", "t", ".", "base", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "}" ]
// RoundTrip implements the http.RoundTripper interface.
[ "RoundTrip", "implements", "the", "http", ".", "RoundTripper", "interface", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/transport.go#L30-L58
149,718
golang/gddo
log/log.go
FromContext
func FromContext(ctx context.Context) log15.Logger { if logger, ok := ctx.Value(loggerKey).(log15.Logger); ok { return logger } return log15.Root() }
go
func FromContext(ctx context.Context) log15.Logger { if logger, ok := ctx.Value(loggerKey).(log15.Logger); ok { return logger } return log15.Root() }
[ "func", "FromContext", "(", "ctx", "context", ".", "Context", ")", "log15", ".", "Logger", "{", "if", "logger", ",", "ok", ":=", "ctx", ".", "Value", "(", "loggerKey", ")", ".", "(", "log15", ".", "Logger", ")", ";", "ok", "{", "return", "logger", "\n", "}", "\n\n", "return", "log15", ".", "Root", "(", ")", "\n", "}" ]
// FromContext always returns a logger. If there is no logger in the context, it // returns the root logger. It is not recommended for use and may be removed in // the future.
[ "FromContext", "always", "returns", "a", "logger", ".", "If", "there", "is", "no", "logger", "in", "the", "context", "it", "returns", "the", "root", "logger", ".", "It", "is", "not", "recommended", "for", "use", "and", "may", "be", "removed", "in", "the", "future", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/log/log.go#L21-L27
149,719
golang/gddo
log/log.go
NewContext
func NewContext(ctx context.Context, l log15.Logger) context.Context { return context.WithValue(ctx, loggerKey, l) }
go
func NewContext(ctx context.Context, l log15.Logger) context.Context { return context.WithValue(ctx, loggerKey, l) }
[ "func", "NewContext", "(", "ctx", "context", ".", "Context", ",", "l", "log15", ".", "Logger", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "loggerKey", ",", "l", ")", "\n", "}" ]
// NewContext creates a new context containing the given logger. It is not // recommended for use and may be removed in the future.
[ "NewContext", "creates", "a", "new", "context", "containing", "the", "given", "logger", ".", "It", "is", "not", "recommended", "for", "use", "and", "may", "be", "removed", "in", "the", "future", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/log/log.go#L31-L33
149,720
golang/gddo
gosrc/client.go
get
func (c *httpClient) get(ctx context.Context, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Take the trace ID to group all outbound requests together. req = req.WithContext(ctx) for k, vs := range c.header { req.Header[k] = vs } resp, err := c.client.Do(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
go
func (c *httpClient) get(ctx context.Context, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Take the trace ID to group all outbound requests together. req = req.WithContext(ctx) for k, vs := range c.header { req.Header[k] = vs } resp, err := c.client.Do(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
[ "func", "(", "c", "*", "httpClient", ")", "get", "(", "ctx", "context", ".", "Context", ",", "url", "string", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Take the trace ID to group all outbound requests together.", "req", "=", "req", ".", "WithContext", "(", "ctx", ")", "\n", "for", "k", ",", "vs", ":=", "range", "c", ".", "header", "{", "req", ".", "Header", "[", "k", "]", "=", "vs", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "RemoteError", "{", "req", ".", "URL", ".", "Host", ",", "err", "}", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// get issues a GET to the specified URL.
[ "get", "issues", "a", "GET", "to", "the", "specified", "URL", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/client.go#L35-L51
149,721
golang/gddo
gosrc/client.go
getNoFollow
func (c *httpClient) getNoFollow(url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, vs := range c.header { req.Header[k] = vs } t := c.client.Transport if t == nil { t = http.DefaultTransport } resp, err := t.RoundTrip(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
go
func (c *httpClient) getNoFollow(url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, vs := range c.header { req.Header[k] = vs } t := c.client.Transport if t == nil { t = http.DefaultTransport } resp, err := t.RoundTrip(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
[ "func", "(", "c", "*", "httpClient", ")", "getNoFollow", "(", "url", "string", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "k", ",", "vs", ":=", "range", "c", ".", "header", "{", "req", ".", "Header", "[", "k", "]", "=", "vs", "\n", "}", "\n", "t", ":=", "c", ".", "client", ".", "Transport", "\n", "if", "t", "==", "nil", "{", "t", "=", "http", ".", "DefaultTransport", "\n", "}", "\n", "resp", ",", "err", ":=", "t", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "RemoteError", "{", "req", ".", "URL", ".", "Host", ",", "err", "}", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// getNoFollow issues a GET to the specified URL without following redirects.
[ "getNoFollow", "issues", "a", "GET", "to", "the", "specified", "URL", "without", "following", "redirects", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/client.go#L54-L71
149,722
golang/gddo
database/indexae.go
putIndex
func putIndex(c context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if id == "" { return errors.New("indexae: no id assigned") } idx, err := search.Open("packages") if err != nil { return err } var pkg Package if err := idx.Get(c, id, &pkg); err != nil { if err != search.ErrNoSuchDocument { return err } else if pdoc == nil { // Cannot update a non-existing document. return errors.New("indexae: cannot create new document with nil pdoc") } // No such document in the index, fall through. } // Update document information accordingly. if pdoc != nil { pkg.Name = pdoc.Name pkg.Path = pdoc.ImportPath pkg.Synopsis = pdoc.Synopsis pkg.Stars = pdoc.Stars pkg.Fork = pdoc.Fork } if score >= 0 { pkg.Score = score } pkg.ImportCount = importCount if _, err := idx.Put(c, id, &pkg); err != nil { return err } return nil }
go
func putIndex(c context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if id == "" { return errors.New("indexae: no id assigned") } idx, err := search.Open("packages") if err != nil { return err } var pkg Package if err := idx.Get(c, id, &pkg); err != nil { if err != search.ErrNoSuchDocument { return err } else if pdoc == nil { // Cannot update a non-existing document. return errors.New("indexae: cannot create new document with nil pdoc") } // No such document in the index, fall through. } // Update document information accordingly. if pdoc != nil { pkg.Name = pdoc.Name pkg.Path = pdoc.ImportPath pkg.Synopsis = pdoc.Synopsis pkg.Stars = pdoc.Stars pkg.Fork = pdoc.Fork } if score >= 0 { pkg.Score = score } pkg.ImportCount = importCount if _, err := idx.Put(c, id, &pkg); err != nil { return err } return nil }
[ "func", "putIndex", "(", "c", "context", ".", "Context", ",", "pdoc", "*", "doc", ".", "Package", ",", "id", "string", ",", "score", "float64", ",", "importCount", "int", ")", "error", "{", "if", "id", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "idx", ",", "err", ":=", "search", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "pkg", "Package", "\n", "if", "err", ":=", "idx", ".", "Get", "(", "c", ",", "id", ",", "&", "pkg", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "search", ".", "ErrNoSuchDocument", "{", "return", "err", "\n", "}", "else", "if", "pdoc", "==", "nil", "{", "// Cannot update a non-existing document.", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// No such document in the index, fall through.", "}", "\n\n", "// Update document information accordingly.", "if", "pdoc", "!=", "nil", "{", "pkg", ".", "Name", "=", "pdoc", ".", "Name", "\n", "pkg", ".", "Path", "=", "pdoc", ".", "ImportPath", "\n", "pkg", ".", "Synopsis", "=", "pdoc", ".", "Synopsis", "\n", "pkg", ".", "Stars", "=", "pdoc", ".", "Stars", "\n", "pkg", ".", "Fork", "=", "pdoc", ".", "Fork", "\n", "}", "\n", "if", "score", ">=", "0", "{", "pkg", ".", "Score", "=", "score", "\n", "}", "\n", "pkg", ".", "ImportCount", "=", "importCount", "\n\n", "if", "_", ",", "err", ":=", "idx", ".", "Put", "(", "c", ",", "id", ",", "&", "pkg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putIndex creates or updates a package entry in the search index. id identifies the document in the index. // If pdoc is non-nil, putIndex will update the package's name, path and synopsis supplied by pdoc. // pdoc must be non-nil for a package's first call to putIndex. // putIndex updates the Score to score, if non-negative.
[ "putIndex", "creates", "or", "updates", "a", "package", "entry", "in", "the", "search", "index", ".", "id", "identifies", "the", "document", "in", "the", "index", ".", "If", "pdoc", "is", "non", "-", "nil", "putIndex", "will", "update", "the", "package", "s", "name", "path", "and", "synopsis", "supplied", "by", "pdoc", ".", "pdoc", "must", "be", "non", "-", "nil", "for", "a", "package", "s", "first", "call", "to", "putIndex", ".", "putIndex", "updates", "the", "Score", "to", "score", "if", "non", "-", "negative", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/indexae.go#L91-L128
149,723
golang/gddo
database/indexae.go
searchAE
func searchAE(c context.Context, q string) ([]Package, error) { index, err := search.Open("packages") if err != nil { return nil, err } var pkgs []Package opt := &search.SearchOptions{ Limit: 100, } for it := index.Search(c, parseQuery2(q), opt); ; { var p Package _, err := it.Next(&p) if err == search.Done { break } if err != nil { return nil, err } pkgs = append(pkgs, p) } return pkgs, nil }
go
func searchAE(c context.Context, q string) ([]Package, error) { index, err := search.Open("packages") if err != nil { return nil, err } var pkgs []Package opt := &search.SearchOptions{ Limit: 100, } for it := index.Search(c, parseQuery2(q), opt); ; { var p Package _, err := it.Next(&p) if err == search.Done { break } if err != nil { return nil, err } pkgs = append(pkgs, p) } return pkgs, nil }
[ "func", "searchAE", "(", "c", "context", ".", "Context", ",", "q", "string", ")", "(", "[", "]", "Package", ",", "error", ")", "{", "index", ",", "err", ":=", "search", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "pkgs", "[", "]", "Package", "\n", "opt", ":=", "&", "search", ".", "SearchOptions", "{", "Limit", ":", "100", ",", "}", "\n", "for", "it", ":=", "index", ".", "Search", "(", "c", ",", "parseQuery2", "(", "q", ")", ",", "opt", ")", ";", ";", "{", "var", "p", "Package", "\n", "_", ",", "err", ":=", "it", ".", "Next", "(", "&", "p", ")", "\n", "if", "err", "==", "search", ".", "Done", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pkgs", "=", "append", "(", "pkgs", ",", "p", ")", "\n", "}", "\n", "return", "pkgs", ",", "nil", "\n", "}" ]
// searchAE searches the packages index for a given query. A path-like query string // will be passed in unchanged, whereas single words will be stemmed.
[ "searchAE", "searches", "the", "packages", "index", "for", "a", "given", "query", ".", "A", "path", "-", "like", "query", "string", "will", "be", "passed", "in", "unchanged", "whereas", "single", "words", "will", "be", "stemmed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/indexae.go#L132-L153
149,724
golang/gddo
gddo-server/crawl.go
isActivePkg
func (s *server) isActivePkg(pkg string, status gosrc.DirectoryStatus) bool { switch status { case gosrc.Active: return true case gosrc.NoRecentCommits: // It should be inactive only if it has no imports as well. n, err := s.db.ImporterCount(pkg) if err != nil { log.Printf("ERROR db.ImporterCount(%q): %v", pkg, err) } return n > 0 } return false }
go
func (s *server) isActivePkg(pkg string, status gosrc.DirectoryStatus) bool { switch status { case gosrc.Active: return true case gosrc.NoRecentCommits: // It should be inactive only if it has no imports as well. n, err := s.db.ImporterCount(pkg) if err != nil { log.Printf("ERROR db.ImporterCount(%q): %v", pkg, err) } return n > 0 } return false }
[ "func", "(", "s", "*", "server", ")", "isActivePkg", "(", "pkg", "string", ",", "status", "gosrc", ".", "DirectoryStatus", ")", "bool", "{", "switch", "status", "{", "case", "gosrc", ".", "Active", ":", "return", "true", "\n", "case", "gosrc", ".", "NoRecentCommits", ":", "// It should be inactive only if it has no imports as well.", "n", ",", "err", ":=", "s", ".", "db", ".", "ImporterCount", "(", "pkg", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "pkg", ",", "err", ")", "\n", "}", "\n", "return", "n", ">", "0", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isActivePkg reports whether a package is considered active, // either because its directory is active or because it is imported by another package.
[ "isActivePkg", "reports", "whether", "a", "package", "is", "considered", "active", "either", "because", "its", "directory", "is", "active", "or", "because", "it", "is", "imported", "by", "another", "package", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/crawl.go#L158-L171
149,725
golang/gddo
internal/health/health.go
Add
func (h *Handler) Add(c Checker) { h.checkers = append(h.checkers, c) }
go
func (h *Handler) Add(c Checker) { h.checkers = append(h.checkers, c) }
[ "func", "(", "h", "*", "Handler", ")", "Add", "(", "c", "Checker", ")", "{", "h", ".", "checkers", "=", "append", "(", "h", ".", "checkers", ",", "c", ")", "\n", "}" ]
// Add adds a new check to the handler.
[ "Add", "adds", "a", "new", "check", "to", "the", "handler", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/internal/health/health.go#L22-L24
149,726
golang/gddo
internal/health/health.go
ServeHTTP
func (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) { for _, c := range h.checkers { if err := c.CheckHealth(); err != nil { writeUnhealthy(w) return } } writeHealthy(w) }
go
func (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) { for _, c := range h.checkers { if err := c.CheckHealth(); err != nil { writeUnhealthy(w) return } } writeHealthy(w) }
[ "func", "(", "h", "*", "Handler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "for", "_", ",", "c", ":=", "range", "h", ".", "checkers", "{", "if", "err", ":=", "c", ".", "CheckHealth", "(", ")", ";", "err", "!=", "nil", "{", "writeUnhealthy", "(", "w", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "writeHealthy", "(", "w", ")", "\n", "}" ]
// ServeHTTP returns 200 if it is healthy, 500 otherwise.
[ "ServeHTTP", "returns", "200", "if", "it", "is", "healthy", "500", "otherwise", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/internal/health/health.go#L27-L35
149,727
golang/gddo
gddo-server/logging.go
LogEvent
func (g *GCELogger) LogEvent(w http.ResponseWriter, r *http.Request, content interface{}) { const sessionCookieName = "GODOC_ORG_SESSION_ID" cookie, err := r.Cookie(sessionCookieName) if err != nil { // Generates a random session id and sends it in response. rs, err := randomString() if err != nil { log.Println("error generating a random session id: ", err) return } // This cookie is intentionally short-lived and contains no information // that might identify the user. Its sole purpose is to tie query // terms and destination pages together to measure search quality. cookie = &http.Cookie{ Name: sessionCookieName, Value: rs, Expires: time.Now().Add(time.Hour), } http.SetCookie(w, cookie) } // We must not record the client's IP address, or any other information // that might compromise the user's privacy. payload := map[string]interface{}{ sessionCookieName: cookie.Value, "path": r.URL.RequestURI(), "method": r.Method, "referer": r.Referer(), } if pkgs, ok := content.([]database.Package); ok { payload["packages"] = pkgs } // Log queues the entry to its internal buffer, or discarding the entry // if the buffer was full. g.cli.Log(logging.Entry{ Payload: payload, }) }
go
func (g *GCELogger) LogEvent(w http.ResponseWriter, r *http.Request, content interface{}) { const sessionCookieName = "GODOC_ORG_SESSION_ID" cookie, err := r.Cookie(sessionCookieName) if err != nil { // Generates a random session id and sends it in response. rs, err := randomString() if err != nil { log.Println("error generating a random session id: ", err) return } // This cookie is intentionally short-lived and contains no information // that might identify the user. Its sole purpose is to tie query // terms and destination pages together to measure search quality. cookie = &http.Cookie{ Name: sessionCookieName, Value: rs, Expires: time.Now().Add(time.Hour), } http.SetCookie(w, cookie) } // We must not record the client's IP address, or any other information // that might compromise the user's privacy. payload := map[string]interface{}{ sessionCookieName: cookie.Value, "path": r.URL.RequestURI(), "method": r.Method, "referer": r.Referer(), } if pkgs, ok := content.([]database.Package); ok { payload["packages"] = pkgs } // Log queues the entry to its internal buffer, or discarding the entry // if the buffer was full. g.cli.Log(logging.Entry{ Payload: payload, }) }
[ "func", "(", "g", "*", "GCELogger", ")", "LogEvent", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "content", "interface", "{", "}", ")", "{", "const", "sessionCookieName", "=", "\"", "\"", "\n", "cookie", ",", "err", ":=", "r", ".", "Cookie", "(", "sessionCookieName", ")", "\n", "if", "err", "!=", "nil", "{", "// Generates a random session id and sends it in response.", "rs", ",", "err", ":=", "randomString", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "// This cookie is intentionally short-lived and contains no information", "// that might identify the user. Its sole purpose is to tie query", "// terms and destination pages together to measure search quality.", "cookie", "=", "&", "http", ".", "Cookie", "{", "Name", ":", "sessionCookieName", ",", "Value", ":", "rs", ",", "Expires", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Hour", ")", ",", "}", "\n", "http", ".", "SetCookie", "(", "w", ",", "cookie", ")", "\n", "}", "\n\n", "// We must not record the client's IP address, or any other information", "// that might compromise the user's privacy.", "payload", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "sessionCookieName", ":", "cookie", ".", "Value", ",", "\"", "\"", ":", "r", ".", "URL", ".", "RequestURI", "(", ")", ",", "\"", "\"", ":", "r", ".", "Method", ",", "\"", "\"", ":", "r", ".", "Referer", "(", ")", ",", "}", "\n", "if", "pkgs", ",", "ok", ":=", "content", ".", "(", "[", "]", "database", ".", "Package", ")", ";", "ok", "{", "payload", "[", "\"", "\"", "]", "=", "pkgs", "\n", "}", "\n\n", "// Log queues the entry to its internal buffer, or discarding the entry", "// if the buffer was full.", "g", ".", "cli", ".", "Log", "(", "logging", ".", "Entry", "{", "Payload", ":", "payload", ",", "}", ")", "\n", "}" ]
// LogEvent creates an entry in Cloud Logging to record user's behavior. We should only // use this to log events we are interested in. General request logs are handled by GAE // automatically in request_log and stderr.
[ "LogEvent", "creates", "an", "entry", "in", "Cloud", "Logging", "to", "record", "user", "s", "behavior", ".", "We", "should", "only", "use", "this", "to", "log", "events", "we", "are", "interested", "in", ".", "General", "request", "logs", "are", "handled", "by", "GAE", "automatically", "in", "request_log", "and", "stderr", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/logging.go#L33-L71
149,728
golang/gddo
gosrc/util.go
isDocFile
func isDocFile(n string) bool { if strings.HasSuffix(n, ".go") && n[0] != '_' && n[0] != '.' { return true } return readmePat.MatchString(n) }
go
func isDocFile(n string) bool { if strings.HasSuffix(n, ".go") && n[0] != '_' && n[0] != '.' { return true } return readmePat.MatchString(n) }
[ "func", "isDocFile", "(", "n", "string", ")", "bool", "{", "if", "strings", ".", "HasSuffix", "(", "n", ",", "\"", "\"", ")", "&&", "n", "[", "0", "]", "!=", "'_'", "&&", "n", "[", "0", "]", "!=", "'.'", "{", "return", "true", "\n", "}", "\n", "return", "readmePat", ".", "MatchString", "(", "n", ")", "\n", "}" ]
// isDocFile returns true if a file with name n should be included in the // documentation.
[ "isDocFile", "returns", "true", "if", "a", "file", "with", "name", "n", "should", "be", "included", "in", "the", "documentation", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/util.go#L55-L60
149,729
golang/gddo
gddo-server/main.go
getDoc
func (s *server) getDoc(ctx context.Context, path string, requestType int) (*doc.Package, []database.Package, error) { if path == "-" { // A hack in the database package uses the path "-" to represent the // next document to crawl. Block "-" here so that requests to /- always // return not found. return nil, nil, &httpError{status: http.StatusNotFound} } pdoc, pkgs, nextCrawl, err := s.db.Get(ctx, path) if err != nil { return nil, nil, err } needsCrawl := false switch requestType { case queryRequest, apiRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) == 0 case humanRequest: needsCrawl = nextCrawl.Before(time.Now()) case robotRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) > 0 } if !needsCrawl { return pdoc, pkgs, nil } c := make(chan crawlResult, 1) go func() { pdoc, err := s.crawlDoc(ctx, "web ", path, pdoc, len(pkgs) > 0, nextCrawl) c <- crawlResult{pdoc, err} }() timeout := s.v.GetDuration(ConfigGetTimeout) if pdoc == nil { timeout = s.v.GetDuration(ConfigFirstGetTimeout) } select { case cr := <-c: err = cr.err if err == nil { pdoc = cr.pdoc } case <-time.After(timeout): err = errUpdateTimeout } switch { case err == nil: return pdoc, pkgs, nil case gosrc.IsNotFound(err): return nil, nil, err case pdoc != nil: log.Printf("Serving %q from database after error getting doc: %v", path, err) return pdoc, pkgs, nil case err == errUpdateTimeout: log.Printf("Serving %q as not found after timeout getting doc", path) return nil, nil, &httpError{status: http.StatusNotFound} default: return nil, nil, err } }
go
func (s *server) getDoc(ctx context.Context, path string, requestType int) (*doc.Package, []database.Package, error) { if path == "-" { // A hack in the database package uses the path "-" to represent the // next document to crawl. Block "-" here so that requests to /- always // return not found. return nil, nil, &httpError{status: http.StatusNotFound} } pdoc, pkgs, nextCrawl, err := s.db.Get(ctx, path) if err != nil { return nil, nil, err } needsCrawl := false switch requestType { case queryRequest, apiRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) == 0 case humanRequest: needsCrawl = nextCrawl.Before(time.Now()) case robotRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) > 0 } if !needsCrawl { return pdoc, pkgs, nil } c := make(chan crawlResult, 1) go func() { pdoc, err := s.crawlDoc(ctx, "web ", path, pdoc, len(pkgs) > 0, nextCrawl) c <- crawlResult{pdoc, err} }() timeout := s.v.GetDuration(ConfigGetTimeout) if pdoc == nil { timeout = s.v.GetDuration(ConfigFirstGetTimeout) } select { case cr := <-c: err = cr.err if err == nil { pdoc = cr.pdoc } case <-time.After(timeout): err = errUpdateTimeout } switch { case err == nil: return pdoc, pkgs, nil case gosrc.IsNotFound(err): return nil, nil, err case pdoc != nil: log.Printf("Serving %q from database after error getting doc: %v", path, err) return pdoc, pkgs, nil case err == errUpdateTimeout: log.Printf("Serving %q as not found after timeout getting doc", path) return nil, nil, &httpError{status: http.StatusNotFound} default: return nil, nil, err } }
[ "func", "(", "s", "*", "server", ")", "getDoc", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "requestType", "int", ")", "(", "*", "doc", ".", "Package", ",", "[", "]", "database", ".", "Package", ",", "error", ")", "{", "if", "path", "==", "\"", "\"", "{", "// A hack in the database package uses the path \"-\" to represent the", "// next document to crawl. Block \"-\" here so that requests to /- always", "// return not found.", "return", "nil", ",", "nil", ",", "&", "httpError", "{", "status", ":", "http", ".", "StatusNotFound", "}", "\n", "}", "\n\n", "pdoc", ",", "pkgs", ",", "nextCrawl", ",", "err", ":=", "s", ".", "db", ".", "Get", "(", "ctx", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "needsCrawl", ":=", "false", "\n", "switch", "requestType", "{", "case", "queryRequest", ",", "apiRequest", ":", "needsCrawl", "=", "nextCrawl", ".", "IsZero", "(", ")", "&&", "len", "(", "pkgs", ")", "==", "0", "\n", "case", "humanRequest", ":", "needsCrawl", "=", "nextCrawl", ".", "Before", "(", "time", ".", "Now", "(", ")", ")", "\n", "case", "robotRequest", ":", "needsCrawl", "=", "nextCrawl", ".", "IsZero", "(", ")", "&&", "len", "(", "pkgs", ")", ">", "0", "\n", "}", "\n\n", "if", "!", "needsCrawl", "{", "return", "pdoc", ",", "pkgs", ",", "nil", "\n", "}", "\n\n", "c", ":=", "make", "(", "chan", "crawlResult", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "pdoc", ",", "err", ":=", "s", ".", "crawlDoc", "(", "ctx", ",", "\"", "\"", ",", "path", ",", "pdoc", ",", "len", "(", "pkgs", ")", ">", "0", ",", "nextCrawl", ")", "\n", "c", "<-", "crawlResult", "{", "pdoc", ",", "err", "}", "\n", "}", "(", ")", "\n\n", "timeout", ":=", "s", ".", "v", ".", "GetDuration", "(", "ConfigGetTimeout", ")", "\n", "if", "pdoc", "==", "nil", "{", "timeout", "=", "s", ".", "v", ".", "GetDuration", "(", "ConfigFirstGetTimeout", ")", "\n", "}", "\n\n", "select", "{", "case", "cr", ":=", "<-", "c", ":", "err", "=", "cr", ".", "err", "\n", "if", "err", "==", "nil", "{", "pdoc", "=", "cr", ".", "pdoc", "\n", "}", "\n", "case", "<-", "time", ".", "After", "(", "timeout", ")", ":", "err", "=", "errUpdateTimeout", "\n", "}", "\n\n", "switch", "{", "case", "err", "==", "nil", ":", "return", "pdoc", ",", "pkgs", ",", "nil", "\n", "case", "gosrc", ".", "IsNotFound", "(", "err", ")", ":", "return", "nil", ",", "nil", ",", "err", "\n", "case", "pdoc", "!=", "nil", ":", "log", ".", "Printf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "return", "pdoc", ",", "pkgs", ",", "nil", "\n", "case", "err", "==", "errUpdateTimeout", ":", "log", ".", "Printf", "(", "\"", "\"", ",", "path", ")", "\n", "return", "nil", ",", "nil", ",", "&", "httpError", "{", "status", ":", "http", ".", "StatusNotFound", "}", "\n", "default", ":", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}" ]
// getDoc gets the package documentation from the database or from the version // control system as needed.
[ "getDoc", "gets", "the", "package", "documentation", "from", "the", "database", "or", "from", "the", "version", "control", "system", "as", "needed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/main.go#L78-L140
149,730
golang/gddo
gddo-server/main.go
httpEtag
func (s *server) httpEtag(pdoc *doc.Package, pkgs []database.Package, importerCount int, flashMessages []flashMessage) string { b := make([]byte, 0, 128) b = strconv.AppendInt(b, pdoc.Updated.Unix(), 16) b = append(b, 0) b = append(b, pdoc.Etag...) if importerCount >= 8 { importerCount = 8 } b = append(b, 0) b = strconv.AppendInt(b, int64(importerCount), 16) for _, pkg := range pkgs { b = append(b, 0) b = append(b, pkg.Path...) b = append(b, 0) b = append(b, pkg.Synopsis...) } if s.v.GetBool(ConfigSidebar) { b = append(b, "\000xsb"...) } for _, m := range flashMessages { b = append(b, 0) b = append(b, m.ID...) for _, a := range m.Args { b = append(b, 1) b = append(b, a...) } } h := md5.New() h.Write(b) b = h.Sum(b[:0]) return fmt.Sprintf("\"%x\"", b) }
go
func (s *server) httpEtag(pdoc *doc.Package, pkgs []database.Package, importerCount int, flashMessages []flashMessage) string { b := make([]byte, 0, 128) b = strconv.AppendInt(b, pdoc.Updated.Unix(), 16) b = append(b, 0) b = append(b, pdoc.Etag...) if importerCount >= 8 { importerCount = 8 } b = append(b, 0) b = strconv.AppendInt(b, int64(importerCount), 16) for _, pkg := range pkgs { b = append(b, 0) b = append(b, pkg.Path...) b = append(b, 0) b = append(b, pkg.Synopsis...) } if s.v.GetBool(ConfigSidebar) { b = append(b, "\000xsb"...) } for _, m := range flashMessages { b = append(b, 0) b = append(b, m.ID...) for _, a := range m.Args { b = append(b, 1) b = append(b, a...) } } h := md5.New() h.Write(b) b = h.Sum(b[:0]) return fmt.Sprintf("\"%x\"", b) }
[ "func", "(", "s", "*", "server", ")", "httpEtag", "(", "pdoc", "*", "doc", ".", "Package", ",", "pkgs", "[", "]", "database", ".", "Package", ",", "importerCount", "int", ",", "flashMessages", "[", "]", "flashMessage", ")", "string", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "128", ")", "\n", "b", "=", "strconv", ".", "AppendInt", "(", "b", ",", "pdoc", ".", "Updated", ".", "Unix", "(", ")", ",", "16", ")", "\n", "b", "=", "append", "(", "b", ",", "0", ")", "\n", "b", "=", "append", "(", "b", ",", "pdoc", ".", "Etag", "...", ")", "\n", "if", "importerCount", ">=", "8", "{", "importerCount", "=", "8", "\n", "}", "\n", "b", "=", "append", "(", "b", ",", "0", ")", "\n", "b", "=", "strconv", ".", "AppendInt", "(", "b", ",", "int64", "(", "importerCount", ")", ",", "16", ")", "\n", "for", "_", ",", "pkg", ":=", "range", "pkgs", "{", "b", "=", "append", "(", "b", ",", "0", ")", "\n", "b", "=", "append", "(", "b", ",", "pkg", ".", "Path", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "0", ")", "\n", "b", "=", "append", "(", "b", ",", "pkg", ".", "Synopsis", "...", ")", "\n", "}", "\n", "if", "s", ".", "v", ".", "GetBool", "(", "ConfigSidebar", ")", "{", "b", "=", "append", "(", "b", ",", "\"", "\\000", "\"", "...", ")", "\n", "}", "\n", "for", "_", ",", "m", ":=", "range", "flashMessages", "{", "b", "=", "append", "(", "b", ",", "0", ")", "\n", "b", "=", "append", "(", "b", ",", "m", ".", "ID", "...", ")", "\n", "for", "_", ",", "a", ":=", "range", "m", ".", "Args", "{", "b", "=", "append", "(", "b", ",", "1", ")", "\n", "b", "=", "append", "(", "b", ",", "a", "...", ")", "\n", "}", "\n", "}", "\n", "h", ":=", "md5", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "b", ")", "\n", "b", "=", "h", ".", "Sum", "(", "b", "[", ":", "0", "]", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "b", ")", "\n", "}" ]
// httpEtag returns the package entity tag used in HTTP transactions.
[ "httpEtag", "returns", "the", "package", "entity", "tag", "used", "in", "HTTP", "transactions", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/main.go#L179-L210
149,731
golang/gddo
gddo-server/config.go
setDefaults
func setDefaults(v *viper.Viper) { // ConfigGAERemoteAPI is based on project. project := v.GetString(ConfigProject) if project != "" { defaultEndpoint := fmt.Sprintf("serviceproxy-dot-%s.appspot.com", project) v.SetDefault(ConfigGAERemoteAPI, defaultEndpoint) } }
go
func setDefaults(v *viper.Viper) { // ConfigGAERemoteAPI is based on project. project := v.GetString(ConfigProject) if project != "" { defaultEndpoint := fmt.Sprintf("serviceproxy-dot-%s.appspot.com", project) v.SetDefault(ConfigGAERemoteAPI, defaultEndpoint) } }
[ "func", "setDefaults", "(", "v", "*", "viper", ".", "Viper", ")", "{", "// ConfigGAERemoteAPI is based on project.", "project", ":=", "v", ".", "GetString", "(", "ConfigProject", ")", "\n", "if", "project", "!=", "\"", "\"", "{", "defaultEndpoint", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "project", ")", "\n", "v", ".", "SetDefault", "(", "ConfigGAERemoteAPI", ",", "defaultEndpoint", ")", "\n", "}", "\n", "}" ]
// setDefaults sets defaults for configuration options that depend on other // configuration options. This allows for smart defaults but allows for // overrides.
[ "setDefaults", "sets", "defaults", "for", "configuration", "options", "that", "depend", "on", "other", "configuration", "options", ".", "This", "allows", "for", "smart", "defaults", "but", "allows", "for", "overrides", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/config.go#L141-L148
149,732
golang/gddo
gddo-server/config.go
readViperConfig
func readViperConfig(ctx context.Context, v *viper.Viper) error { v.AddConfigPath(".") v.AddConfigPath("/etc") v.SetConfigName("gddo") if v.GetString("config") != "" { v.SetConfigFile(v.GetString("config")) } if err := v.ReadInConfig(); err != nil { // If a config exists but could not be parsed, we should bail. if _, ok := err.(viper.ConfigParseError); ok { return fmt.Errorf("parse config: %v", err) } // If the user specified a config file location in flags or env and // we failed to load it, we should bail. If not, it is just a warning. if v.GetString("config") != "" { return fmt.Errorf("load config: %v", err) } log.Warn(ctx, "failed to load configuration file", "error", err) return nil } log.Info(ctx, "loaded configuration file successfully", "path", v.ConfigFileUsed()) return nil }
go
func readViperConfig(ctx context.Context, v *viper.Viper) error { v.AddConfigPath(".") v.AddConfigPath("/etc") v.SetConfigName("gddo") if v.GetString("config") != "" { v.SetConfigFile(v.GetString("config")) } if err := v.ReadInConfig(); err != nil { // If a config exists but could not be parsed, we should bail. if _, ok := err.(viper.ConfigParseError); ok { return fmt.Errorf("parse config: %v", err) } // If the user specified a config file location in flags or env and // we failed to load it, we should bail. If not, it is just a warning. if v.GetString("config") != "" { return fmt.Errorf("load config: %v", err) } log.Warn(ctx, "failed to load configuration file", "error", err) return nil } log.Info(ctx, "loaded configuration file successfully", "path", v.ConfigFileUsed()) return nil }
[ "func", "readViperConfig", "(", "ctx", "context", ".", "Context", ",", "v", "*", "viper", ".", "Viper", ")", "error", "{", "v", ".", "AddConfigPath", "(", "\"", "\"", ")", "\n", "v", ".", "AddConfigPath", "(", "\"", "\"", ")", "\n", "v", ".", "SetConfigName", "(", "\"", "\"", ")", "\n", "if", "v", ".", "GetString", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "v", ".", "SetConfigFile", "(", "v", ".", "GetString", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "v", ".", "ReadInConfig", "(", ")", ";", "err", "!=", "nil", "{", "// If a config exists but could not be parsed, we should bail.", "if", "_", ",", "ok", ":=", "err", ".", "(", "viper", ".", "ConfigParseError", ")", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// If the user specified a config file location in flags or env and", "// we failed to load it, we should bail. If not, it is just a warning.", "if", "v", ".", "GetString", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Warn", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "log", ".", "Info", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "v", ".", "ConfigFileUsed", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// readViperConfig finds and then parses a config file. It will return // an error if the config file was specified or could not parse. // Otherwise it will only warn that it failed to load the config.
[ "readViperConfig", "finds", "and", "then", "parses", "a", "config", "file", ".", "It", "will", "return", "an", "error", "if", "the", "config", "file", "was", "specified", "or", "could", "not", "parse", ".", "Otherwise", "it", "will", "only", "warn", "that", "it", "failed", "to", "load", "the", "config", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/config.go#L183-L207
149,733
golang/gddo
httputil/buster.go
Get
func (cb *CacheBusters) Get(path string) string { cb.mu.Lock() if cb.tokens == nil { cb.tokens = make(map[string]string) } token, ok := cb.tokens[path] cb.mu.Unlock() if ok { return token } w := busterWriter{ Writer: ioutil.Discard, headerMap: make(http.Header), } r := &http.Request{URL: &url.URL{Path: path}, Method: "HEAD"} cb.Handler.ServeHTTP(&w, r) if w.status == 200 { token = w.headerMap.Get("Etag") if token == "" { token = w.headerMap.Get("Last-Modified") } token = strings.Trim(token, `" `) token = strings.Map(sanitizeTokenRune, token) } cb.mu.Lock() cb.tokens[path] = token cb.mu.Unlock() return token }
go
func (cb *CacheBusters) Get(path string) string { cb.mu.Lock() if cb.tokens == nil { cb.tokens = make(map[string]string) } token, ok := cb.tokens[path] cb.mu.Unlock() if ok { return token } w := busterWriter{ Writer: ioutil.Discard, headerMap: make(http.Header), } r := &http.Request{URL: &url.URL{Path: path}, Method: "HEAD"} cb.Handler.ServeHTTP(&w, r) if w.status == 200 { token = w.headerMap.Get("Etag") if token == "" { token = w.headerMap.Get("Last-Modified") } token = strings.Trim(token, `" `) token = strings.Map(sanitizeTokenRune, token) } cb.mu.Lock() cb.tokens[path] = token cb.mu.Unlock() return token }
[ "func", "(", "cb", "*", "CacheBusters", ")", "Get", "(", "path", "string", ")", "string", "{", "cb", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "cb", ".", "tokens", "==", "nil", "{", "cb", ".", "tokens", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "token", ",", "ok", ":=", "cb", ".", "tokens", "[", "path", "]", "\n", "cb", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "ok", "{", "return", "token", "\n", "}", "\n\n", "w", ":=", "busterWriter", "{", "Writer", ":", "ioutil", ".", "Discard", ",", "headerMap", ":", "make", "(", "http", ".", "Header", ")", ",", "}", "\n", "r", ":=", "&", "http", ".", "Request", "{", "URL", ":", "&", "url", ".", "URL", "{", "Path", ":", "path", "}", ",", "Method", ":", "\"", "\"", "}", "\n", "cb", ".", "Handler", ".", "ServeHTTP", "(", "&", "w", ",", "r", ")", "\n\n", "if", "w", ".", "status", "==", "200", "{", "token", "=", "w", ".", "headerMap", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "token", "==", "\"", "\"", "{", "token", "=", "w", ".", "headerMap", ".", "Get", "(", "\"", "\"", ")", "\n", "}", "\n", "token", "=", "strings", ".", "Trim", "(", "token", ",", "`\" `", ")", "\n", "token", "=", "strings", ".", "Map", "(", "sanitizeTokenRune", ",", "token", ")", "\n", "}", "\n\n", "cb", ".", "mu", ".", "Lock", "(", ")", "\n", "cb", ".", "tokens", "[", "path", "]", "=", "token", "\n", "cb", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "token", "\n", "}" ]
// Get returns the cache busting token for path. If the token is not already // cached, Get issues a HEAD request on handler and uses the response ETag and // Last-Modified headers to compute a token.
[ "Get", "returns", "the", "cache", "busting", "token", "for", "path", ".", "If", "the", "token", "is", "not", "already", "cached", "Get", "issues", "a", "HEAD", "request", "on", "handler", "and", "uses", "the", "response", "ETag", "and", "Last", "-", "Modified", "headers", "to", "compute", "a", "token", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/buster.go#L54-L86
149,734
golang/gddo
httputil/buster.go
AppendQueryParam
func (cb *CacheBusters) AppendQueryParam(path string, name string) string { token := cb.Get(path) if token == "" { return path } return path + "?" + name + "=" + token }
go
func (cb *CacheBusters) AppendQueryParam(path string, name string) string { token := cb.Get(path) if token == "" { return path } return path + "?" + name + "=" + token }
[ "func", "(", "cb", "*", "CacheBusters", ")", "AppendQueryParam", "(", "path", "string", ",", "name", "string", ")", "string", "{", "token", ":=", "cb", ".", "Get", "(", "path", ")", "\n", "if", "token", "==", "\"", "\"", "{", "return", "path", "\n", "}", "\n", "return", "path", "+", "\"", "\"", "+", "name", "+", "\"", "\"", "+", "token", "\n", "}" ]
// AppendQueryParam appends the token as a query parameter to path.
[ "AppendQueryParam", "appends", "the", "token", "as", "a", "query", "parameter", "to", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/buster.go#L89-L95
149,735
golang/gddo
gddo-server/browse.go
isBrowseURL
func isBrowseURL(s string) (importPath string, ok bool) { for _, c := range browsePatterns { if m := c.pat.FindStringSubmatch(s); m != nil { return c.fn(m), true } } return "", false }
go
func isBrowseURL(s string) (importPath string, ok bool) { for _, c := range browsePatterns { if m := c.pat.FindStringSubmatch(s); m != nil { return c.fn(m), true } } return "", false }
[ "func", "isBrowseURL", "(", "s", "string", ")", "(", "importPath", "string", ",", "ok", "bool", ")", "{", "for", "_", ",", "c", ":=", "range", "browsePatterns", "{", "if", "m", ":=", "c", ".", "pat", ".", "FindStringSubmatch", "(", "s", ")", ";", "m", "!=", "nil", "{", "return", "c", ".", "fn", "(", "m", ")", ",", "true", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "false", "\n", "}" ]
// isBrowserURL returns importPath and true if URL looks like a URL for a VCS // source browser.
[ "isBrowserURL", "returns", "importPath", "and", "true", "if", "URL", "looks", "like", "a", "URL", "for", "a", "VCS", "source", "browser", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/browse.go#L90-L97
149,736
golang/gddo
gosrc/path.go
IsValidRemotePath
func IsValidRemotePath(importPath string) bool { parts := strings.Split(importPath, "/") if !validTLDs[path.Ext(parts[0])] { return false } if !validHost.MatchString(parts[0]) { return false } for _, part := range parts[1:] { if !isValidPathElement(part) { return false } } return true }
go
func IsValidRemotePath(importPath string) bool { parts := strings.Split(importPath, "/") if !validTLDs[path.Ext(parts[0])] { return false } if !validHost.MatchString(parts[0]) { return false } for _, part := range parts[1:] { if !isValidPathElement(part) { return false } } return true }
[ "func", "IsValidRemotePath", "(", "importPath", "string", ")", "bool", "{", "parts", ":=", "strings", ".", "Split", "(", "importPath", ",", "\"", "\"", ")", "\n\n", "if", "!", "validTLDs", "[", "path", ".", "Ext", "(", "parts", "[", "0", "]", ")", "]", "{", "return", "false", "\n", "}", "\n\n", "if", "!", "validHost", ".", "MatchString", "(", "parts", "[", "0", "]", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "part", ":=", "range", "parts", "[", "1", ":", "]", "{", "if", "!", "isValidPathElement", "(", "part", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// IsValidRemotePath returns true if importPath is structurally valid for "go get".
[ "IsValidRemotePath", "returns", "true", "if", "importPath", "is", "structurally", "valid", "for", "go", "get", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/path.go#L25-L44
149,737
golang/gddo
gosrc/path.go
IsValidPath
func IsValidPath(importPath string) bool { return pathFlags[importPath]&packagePath != 0 || pathFlags["vendor/"+importPath]&packagePath != 0 || IsValidRemotePath(importPath) }
go
func IsValidPath(importPath string) bool { return pathFlags[importPath]&packagePath != 0 || pathFlags["vendor/"+importPath]&packagePath != 0 || IsValidRemotePath(importPath) }
[ "func", "IsValidPath", "(", "importPath", "string", ")", "bool", "{", "return", "pathFlags", "[", "importPath", "]", "&", "packagePath", "!=", "0", "||", "pathFlags", "[", "\"", "\"", "+", "importPath", "]", "&", "packagePath", "!=", "0", "||", "IsValidRemotePath", "(", "importPath", ")", "\n", "}" ]
// IsValidPath returns true if importPath is structurally valid.
[ "IsValidPath", "returns", "true", "if", "importPath", "is", "structurally", "valid", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/path.go#L52-L56
149,738
dchest/captcha
image.go
NewImage
func NewImage(id string, digits []byte, width, height int) *Image { m := new(Image) // Initialize PRNG. m.rng.Seed(deriveSeed(imageSeedPurpose, id, digits)) m.Paletted = image.NewPaletted(image.Rect(0, 0, width, height), m.getRandomPalette()) m.calculateSizes(width, height, len(digits)) // Randomly position captcha inside the image. maxx := width - (m.numWidth+m.dotSize)*len(digits) - m.dotSize maxy := height - m.numHeight - m.dotSize*2 var border int if width > height { border = height / 5 } else { border = width / 5 } x := m.rng.Int(border, maxx-border) y := m.rng.Int(border, maxy-border) // Draw digits. for _, n := range digits { m.drawDigit(font[n], x, y) x += m.numWidth + m.dotSize } // Draw strike-through line. m.strikeThrough() // Apply wave distortion. m.distort(m.rng.Float(5, 10), m.rng.Float(100, 200)) // Fill image with random circles. m.fillWithCircles(circleCount, m.dotSize) return m }
go
func NewImage(id string, digits []byte, width, height int) *Image { m := new(Image) // Initialize PRNG. m.rng.Seed(deriveSeed(imageSeedPurpose, id, digits)) m.Paletted = image.NewPaletted(image.Rect(0, 0, width, height), m.getRandomPalette()) m.calculateSizes(width, height, len(digits)) // Randomly position captcha inside the image. maxx := width - (m.numWidth+m.dotSize)*len(digits) - m.dotSize maxy := height - m.numHeight - m.dotSize*2 var border int if width > height { border = height / 5 } else { border = width / 5 } x := m.rng.Int(border, maxx-border) y := m.rng.Int(border, maxy-border) // Draw digits. for _, n := range digits { m.drawDigit(font[n], x, y) x += m.numWidth + m.dotSize } // Draw strike-through line. m.strikeThrough() // Apply wave distortion. m.distort(m.rng.Float(5, 10), m.rng.Float(100, 200)) // Fill image with random circles. m.fillWithCircles(circleCount, m.dotSize) return m }
[ "func", "NewImage", "(", "id", "string", ",", "digits", "[", "]", "byte", ",", "width", ",", "height", "int", ")", "*", "Image", "{", "m", ":=", "new", "(", "Image", ")", "\n\n", "// Initialize PRNG.", "m", ".", "rng", ".", "Seed", "(", "deriveSeed", "(", "imageSeedPurpose", ",", "id", ",", "digits", ")", ")", "\n\n", "m", ".", "Paletted", "=", "image", ".", "NewPaletted", "(", "image", ".", "Rect", "(", "0", ",", "0", ",", "width", ",", "height", ")", ",", "m", ".", "getRandomPalette", "(", ")", ")", "\n", "m", ".", "calculateSizes", "(", "width", ",", "height", ",", "len", "(", "digits", ")", ")", "\n", "// Randomly position captcha inside the image.", "maxx", ":=", "width", "-", "(", "m", ".", "numWidth", "+", "m", ".", "dotSize", ")", "*", "len", "(", "digits", ")", "-", "m", ".", "dotSize", "\n", "maxy", ":=", "height", "-", "m", ".", "numHeight", "-", "m", ".", "dotSize", "*", "2", "\n", "var", "border", "int", "\n", "if", "width", ">", "height", "{", "border", "=", "height", "/", "5", "\n", "}", "else", "{", "border", "=", "width", "/", "5", "\n", "}", "\n", "x", ":=", "m", ".", "rng", ".", "Int", "(", "border", ",", "maxx", "-", "border", ")", "\n", "y", ":=", "m", ".", "rng", ".", "Int", "(", "border", ",", "maxy", "-", "border", ")", "\n", "// Draw digits.", "for", "_", ",", "n", ":=", "range", "digits", "{", "m", ".", "drawDigit", "(", "font", "[", "n", "]", ",", "x", ",", "y", ")", "\n", "x", "+=", "m", ".", "numWidth", "+", "m", ".", "dotSize", "\n", "}", "\n", "// Draw strike-through line.", "m", ".", "strikeThrough", "(", ")", "\n", "// Apply wave distortion.", "m", ".", "distort", "(", "m", ".", "rng", ".", "Float", "(", "5", ",", "10", ")", ",", "m", ".", "rng", ".", "Float", "(", "100", ",", "200", ")", ")", "\n", "// Fill image with random circles.", "m", ".", "fillWithCircles", "(", "circleCount", ",", "m", ".", "dotSize", ")", "\n", "return", "m", "\n", "}" ]
// NewImage returns a new captcha image of the given width and height with the // given digits, where each digit must be in range 0-9.
[ "NewImage", "returns", "a", "new", "captcha", "image", "of", "the", "given", "width", "and", "height", "with", "the", "given", "digits", "where", "each", "digit", "must", "be", "in", "range", "0", "-", "9", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/image.go#L36-L67
149,739
dchest/captcha
image.go
encodedPNG
func (m *Image) encodedPNG() []byte { var buf bytes.Buffer if err := png.Encode(&buf, m.Paletted); err != nil { panic(err.Error()) } return buf.Bytes() }
go
func (m *Image) encodedPNG() []byte { var buf bytes.Buffer if err := png.Encode(&buf, m.Paletted); err != nil { panic(err.Error()) } return buf.Bytes() }
[ "func", "(", "m", "*", "Image", ")", "encodedPNG", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "png", ".", "Encode", "(", "&", "buf", ",", "m", ".", "Paletted", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", "\n", "}" ]
// encodedPNG encodes an image to PNG and returns // the result as a byte slice.
[ "encodedPNG", "encodes", "an", "image", "to", "PNG", "and", "returns", "the", "result", "as", "a", "byte", "slice", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/image.go#L90-L96
149,740
dchest/captcha
image.go
WriteTo
func (m *Image) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(m.encodedPNG()) return int64(n), err }
go
func (m *Image) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(m.encodedPNG()) return int64(n), err }
[ "func", "(", "m", "*", "Image", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "n", ",", "err", ":=", "w", ".", "Write", "(", "m", ".", "encodedPNG", "(", ")", ")", "\n", "return", "int64", "(", "n", ")", ",", "err", "\n", "}" ]
// WriteTo writes captcha image in PNG format into the given writer.
[ "WriteTo", "writes", "captcha", "image", "in", "PNG", "format", "into", "the", "given", "writer", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/image.go#L99-L102
149,741
dchest/captcha
random.go
randomBytesMod
func randomBytesMod(length int, mod byte) (b []byte) { if length == 0 { return nil } if mod == 0 { panic("captcha: bad mod argument for randomBytesMod") } maxrb := 255 - byte(256%int(mod)) b = make([]byte, length) i := 0 for { r := randomBytes(length + (length / 4)) for _, c := range r { if c > maxrb { // Skip this number to avoid modulo bias. continue } b[i] = c % mod i++ if i == length { return } } } }
go
func randomBytesMod(length int, mod byte) (b []byte) { if length == 0 { return nil } if mod == 0 { panic("captcha: bad mod argument for randomBytesMod") } maxrb := 255 - byte(256%int(mod)) b = make([]byte, length) i := 0 for { r := randomBytes(length + (length / 4)) for _, c := range r { if c > maxrb { // Skip this number to avoid modulo bias. continue } b[i] = c % mod i++ if i == length { return } } } }
[ "func", "randomBytesMod", "(", "length", "int", ",", "mod", "byte", ")", "(", "b", "[", "]", "byte", ")", "{", "if", "length", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "mod", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "maxrb", ":=", "255", "-", "byte", "(", "256", "%", "int", "(", "mod", ")", ")", "\n", "b", "=", "make", "(", "[", "]", "byte", ",", "length", ")", "\n", "i", ":=", "0", "\n", "for", "{", "r", ":=", "randomBytes", "(", "length", "+", "(", "length", "/", "4", ")", ")", "\n", "for", "_", ",", "c", ":=", "range", "r", "{", "if", "c", ">", "maxrb", "{", "// Skip this number to avoid modulo bias.", "continue", "\n", "}", "\n", "b", "[", "i", "]", "=", "c", "%", "mod", "\n", "i", "++", "\n", "if", "i", "==", "length", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}" ]
// randomBytesMod returns a byte slice of the given length, where each byte is // a random number modulo mod.
[ "randomBytesMod", "returns", "a", "byte", "slice", "of", "the", "given", "length", "where", "each", "byte", "is", "a", "random", "number", "modulo", "mod", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/random.go#L74-L99
149,742
dchest/captcha
random.go
randomId
func randomId() string { b := randomBytesMod(idLen, byte(len(idChars))) for i, c := range b { b[i] = idChars[c] } return string(b) }
go
func randomId() string { b := randomBytesMod(idLen, byte(len(idChars))) for i, c := range b { b[i] = idChars[c] } return string(b) }
[ "func", "randomId", "(", ")", "string", "{", "b", ":=", "randomBytesMod", "(", "idLen", ",", "byte", "(", "len", "(", "idChars", ")", ")", ")", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "b", "[", "i", "]", "=", "idChars", "[", "c", "]", "\n", "}", "\n", "return", "string", "(", "b", ")", "\n", "}" ]
// randomId returns a new random id string.
[ "randomId", "returns", "a", "new", "random", "id", "string", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/random.go#L102-L108
149,743
dchest/captcha
siprng.go
Seed
func (p *siprng) Seed(k [16]byte) { p.k0 = binary.LittleEndian.Uint64(k[0:8]) p.k1 = binary.LittleEndian.Uint64(k[8:16]) p.ctr = 1 }
go
func (p *siprng) Seed(k [16]byte) { p.k0 = binary.LittleEndian.Uint64(k[0:8]) p.k1 = binary.LittleEndian.Uint64(k[8:16]) p.ctr = 1 }
[ "func", "(", "p", "*", "siprng", ")", "Seed", "(", "k", "[", "16", "]", "byte", ")", "{", "p", ".", "k0", "=", "binary", ".", "LittleEndian", ".", "Uint64", "(", "k", "[", "0", ":", "8", "]", ")", "\n", "p", ".", "k1", "=", "binary", ".", "LittleEndian", ".", "Uint64", "(", "k", "[", "8", ":", "16", "]", ")", "\n", "p", ".", "ctr", "=", "1", "\n", "}" ]
// Seed sets a new secret seed for PRNG.
[ "Seed", "sets", "a", "new", "secret", "seed", "for", "PRNG", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/siprng.go#L193-L197
149,744
dchest/captcha
siprng.go
Uint64
func (p *siprng) Uint64() uint64 { v := siphash(p.k0, p.k1, p.ctr) p.ctr++ return v }
go
func (p *siprng) Uint64() uint64 { v := siphash(p.k0, p.k1, p.ctr) p.ctr++ return v }
[ "func", "(", "p", "*", "siprng", ")", "Uint64", "(", ")", "uint64", "{", "v", ":=", "siphash", "(", "p", ".", "k0", ",", "p", ".", "k1", ",", "p", ".", "ctr", ")", "\n", "p", ".", "ctr", "++", "\n", "return", "v", "\n", "}" ]
// Uint64 returns a new pseudorandom uint64.
[ "Uint64", "returns", "a", "new", "pseudorandom", "uint64", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/siprng.go#L200-L204
149,745
dchest/captcha
captcha.go
NewLen
func NewLen(length int) (id string) { id = randomId() globalStore.Set(id, RandomDigits(length)) return }
go
func NewLen(length int) (id string) { id = randomId() globalStore.Set(id, RandomDigits(length)) return }
[ "func", "NewLen", "(", "length", "int", ")", "(", "id", "string", ")", "{", "id", "=", "randomId", "(", ")", "\n", "globalStore", ".", "Set", "(", "id", ",", "RandomDigits", "(", "length", ")", ")", "\n", "return", "\n", "}" ]
// NewLen is just like New, but accepts length of a captcha solution as the // argument.
[ "NewLen", "is", "just", "like", "New", "but", "accepts", "length", "of", "a", "captcha", "solution", "as", "the", "argument", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L85-L89
149,746
dchest/captcha
captcha.go
WriteImage
func WriteImage(w io.Writer, id string, width, height int) error { d := globalStore.Get(id, false) if d == nil { return ErrNotFound } _, err := NewImage(id, d, width, height).WriteTo(w) return err }
go
func WriteImage(w io.Writer, id string, width, height int) error { d := globalStore.Get(id, false) if d == nil { return ErrNotFound } _, err := NewImage(id, d, width, height).WriteTo(w) return err }
[ "func", "WriteImage", "(", "w", "io", ".", "Writer", ",", "id", "string", ",", "width", ",", "height", "int", ")", "error", "{", "d", ":=", "globalStore", ".", "Get", "(", "id", ",", "false", ")", "\n", "if", "d", "==", "nil", "{", "return", "ErrNotFound", "\n", "}", "\n", "_", ",", "err", ":=", "NewImage", "(", "id", ",", "d", ",", "width", ",", "height", ")", ".", "WriteTo", "(", "w", ")", "\n", "return", "err", "\n", "}" ]
// WriteImage writes PNG-encoded image representation of the captcha with the // given id. The image will have the given width and height.
[ "WriteImage", "writes", "PNG", "-", "encoded", "image", "representation", "of", "the", "captcha", "with", "the", "given", "id", ".", "The", "image", "will", "have", "the", "given", "width", "and", "height", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L108-L115
149,747
dchest/captcha
captcha.go
Verify
func Verify(id string, digits []byte) bool { if digits == nil || len(digits) == 0 { return false } reald := globalStore.Get(id, true) if reald == nil { return false } return bytes.Equal(digits, reald) }
go
func Verify(id string, digits []byte) bool { if digits == nil || len(digits) == 0 { return false } reald := globalStore.Get(id, true) if reald == nil { return false } return bytes.Equal(digits, reald) }
[ "func", "Verify", "(", "id", "string", ",", "digits", "[", "]", "byte", ")", "bool", "{", "if", "digits", "==", "nil", "||", "len", "(", "digits", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "reald", ":=", "globalStore", ".", "Get", "(", "id", ",", "true", ")", "\n", "if", "reald", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "bytes", ".", "Equal", "(", "digits", ",", "reald", ")", "\n", "}" ]
// Verify returns true if the given digits are the ones that were used to // create the given captcha id. // // The function deletes the captcha with the given id from the internal // storage, so that the same captcha can't be verified anymore.
[ "Verify", "returns", "true", "if", "the", "given", "digits", "are", "the", "ones", "that", "were", "used", "to", "create", "the", "given", "captcha", "id", ".", "The", "function", "deletes", "the", "captcha", "with", "the", "given", "id", "from", "the", "internal", "storage", "so", "that", "the", "same", "captcha", "can", "t", "be", "verified", "anymore", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L134-L143
149,748
dchest/captcha
captcha.go
VerifyString
func VerifyString(id string, digits string) bool { if digits == "" { return false } ns := make([]byte, len(digits)) for i := range ns { d := digits[i] switch { case '0' <= d && d <= '9': ns[i] = d - '0' case d == ' ' || d == ',': // ignore default: return false } } return Verify(id, ns) }
go
func VerifyString(id string, digits string) bool { if digits == "" { return false } ns := make([]byte, len(digits)) for i := range ns { d := digits[i] switch { case '0' <= d && d <= '9': ns[i] = d - '0' case d == ' ' || d == ',': // ignore default: return false } } return Verify(id, ns) }
[ "func", "VerifyString", "(", "id", "string", ",", "digits", "string", ")", "bool", "{", "if", "digits", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "ns", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "digits", ")", ")", "\n", "for", "i", ":=", "range", "ns", "{", "d", ":=", "digits", "[", "i", "]", "\n", "switch", "{", "case", "'0'", "<=", "d", "&&", "d", "<=", "'9'", ":", "ns", "[", "i", "]", "=", "d", "-", "'0'", "\n", "case", "d", "==", "' '", "||", "d", "==", "','", ":", "// ignore", "default", ":", "return", "false", "\n", "}", "\n", "}", "\n", "return", "Verify", "(", "id", ",", "ns", ")", "\n", "}" ]
// VerifyString is like Verify, but accepts a string of digits. It removes // spaces and commas from the string, but any other characters, apart from // digits and listed above, will cause the function to return false.
[ "VerifyString", "is", "like", "Verify", "but", "accepts", "a", "string", "of", "digits", ".", "It", "removes", "spaces", "and", "commas", "from", "the", "string", "but", "any", "other", "characters", "apart", "from", "digits", "and", "listed", "above", "will", "cause", "the", "function", "to", "return", "false", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L148-L165
149,749
dchest/captcha
audio.go
WriteTo
func (a *Audio) WriteTo(w io.Writer) (n int64, err error) { // Calculate padded length of PCM chunk data. bodyLen := uint32(a.body.Len()) paddedBodyLen := bodyLen if bodyLen%2 != 0 { paddedBodyLen++ } totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen // Header. header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size copy(header, waveHeader) // Put the length of whole RIFF chunk. binary.LittleEndian.PutUint32(header[4:], totalLen) // Put the length of WAVE chunk. binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen) // Write header. nn, err := w.Write(header) n = int64(nn) if err != nil { return } // Write data. n, err = a.body.WriteTo(w) n += int64(nn) if err != nil { return } // Pad byte if chunk length is odd. // (As header has even length, we can check if n is odd, not chunk). if bodyLen != paddedBodyLen { w.Write([]byte{0}) n++ } return }
go
func (a *Audio) WriteTo(w io.Writer) (n int64, err error) { // Calculate padded length of PCM chunk data. bodyLen := uint32(a.body.Len()) paddedBodyLen := bodyLen if bodyLen%2 != 0 { paddedBodyLen++ } totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen // Header. header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size copy(header, waveHeader) // Put the length of whole RIFF chunk. binary.LittleEndian.PutUint32(header[4:], totalLen) // Put the length of WAVE chunk. binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen) // Write header. nn, err := w.Write(header) n = int64(nn) if err != nil { return } // Write data. n, err = a.body.WriteTo(w) n += int64(nn) if err != nil { return } // Pad byte if chunk length is odd. // (As header has even length, we can check if n is odd, not chunk). if bodyLen != paddedBodyLen { w.Write([]byte{0}) n++ } return }
[ "func", "(", "a", "*", "Audio", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "// Calculate padded length of PCM chunk data.", "bodyLen", ":=", "uint32", "(", "a", ".", "body", ".", "Len", "(", ")", ")", "\n", "paddedBodyLen", ":=", "bodyLen", "\n", "if", "bodyLen", "%", "2", "!=", "0", "{", "paddedBodyLen", "++", "\n", "}", "\n", "totalLen", ":=", "uint32", "(", "len", "(", "waveHeader", ")", ")", "-", "4", "+", "paddedBodyLen", "\n", "// Header.", "header", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "waveHeader", ")", "+", "4", ")", "// includes 4 bytes for chunk size", "\n", "copy", "(", "header", ",", "waveHeader", ")", "\n", "// Put the length of whole RIFF chunk.", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "header", "[", "4", ":", "]", ",", "totalLen", ")", "\n", "// Put the length of WAVE chunk.", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "header", "[", "len", "(", "waveHeader", ")", ":", "]", ",", "bodyLen", ")", "\n", "// Write header.", "nn", ",", "err", ":=", "w", ".", "Write", "(", "header", ")", "\n", "n", "=", "int64", "(", "nn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// Write data.", "n", ",", "err", "=", "a", ".", "body", ".", "WriteTo", "(", "w", ")", "\n", "n", "+=", "int64", "(", "nn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// Pad byte if chunk length is odd.", "// (As header has even length, we can check if n is odd, not chunk).", "if", "bodyLen", "!=", "paddedBodyLen", "{", "w", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n", "n", "++", "\n", "}", "\n", "return", "\n", "}" ]
// WriteTo writes captcha audio in WAVE format into the given io.Writer, and // returns the number of bytes written and an error if any.
[ "WriteTo", "writes", "captcha", "audio", "in", "WAVE", "format", "into", "the", "given", "io", ".", "Writer", "and", "returns", "the", "number", "of", "bytes", "written", "and", "an", "error", "if", "any", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/audio.go#L85-L119
149,750
dchest/captcha
audio.go
mixSound
func mixSound(dst, src []byte) { for i, v := range src { av := int(v) bv := int(dst[i]) if av < 128 && bv < 128 { dst[i] = byte(av * bv / 128) } else { dst[i] = byte(2*(av+bv) - av*bv/128 - 256) } } }
go
func mixSound(dst, src []byte) { for i, v := range src { av := int(v) bv := int(dst[i]) if av < 128 && bv < 128 { dst[i] = byte(av * bv / 128) } else { dst[i] = byte(2*(av+bv) - av*bv/128 - 256) } } }
[ "func", "mixSound", "(", "dst", ",", "src", "[", "]", "byte", ")", "{", "for", "i", ",", "v", ":=", "range", "src", "{", "av", ":=", "int", "(", "v", ")", "\n", "bv", ":=", "int", "(", "dst", "[", "i", "]", ")", "\n", "if", "av", "<", "128", "&&", "bv", "<", "128", "{", "dst", "[", "i", "]", "=", "byte", "(", "av", "*", "bv", "/", "128", ")", "\n", "}", "else", "{", "dst", "[", "i", "]", "=", "byte", "(", "2", "*", "(", "av", "+", "bv", ")", "-", "av", "*", "bv", "/", "128", "-", "256", ")", "\n", "}", "\n", "}", "\n", "}" ]
// mixSound mixes src into dst. Dst must have length equal to or greater than // src length.
[ "mixSound", "mixes", "src", "into", "dst", ".", "Dst", "must", "have", "length", "equal", "to", "or", "greater", "than", "src", "length", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/audio.go#L172-L182
149,751
google/go-genproto
regen.go
goPkg
func goPkg(fname string) (string, error) { content, err := ioutil.ReadFile(fname) if err != nil { return "", err } var pkgName string if match := goPkgOptRe.FindSubmatch(content); len(match) > 0 { pn, err := strconv.Unquote(string(match[1])) if err != nil { return "", err } pkgName = pn } if p := strings.IndexRune(pkgName, ';'); p > 0 { pkgName = pkgName[:p] } return pkgName, nil }
go
func goPkg(fname string) (string, error) { content, err := ioutil.ReadFile(fname) if err != nil { return "", err } var pkgName string if match := goPkgOptRe.FindSubmatch(content); len(match) > 0 { pn, err := strconv.Unquote(string(match[1])) if err != nil { return "", err } pkgName = pn } if p := strings.IndexRune(pkgName, ';'); p > 0 { pkgName = pkgName[:p] } return pkgName, nil }
[ "func", "goPkg", "(", "fname", "string", ")", "(", "string", ",", "error", ")", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "var", "pkgName", "string", "\n", "if", "match", ":=", "goPkgOptRe", ".", "FindSubmatch", "(", "content", ")", ";", "len", "(", "match", ")", ">", "0", "{", "pn", ",", "err", ":=", "strconv", ".", "Unquote", "(", "string", "(", "match", "[", "1", "]", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "pkgName", "=", "pn", "\n", "}", "\n", "if", "p", ":=", "strings", ".", "IndexRune", "(", "pkgName", ",", "';'", ")", ";", "p", ">", "0", "{", "pkgName", "=", "pkgName", "[", ":", "p", "]", "\n", "}", "\n", "return", "pkgName", ",", "nil", "\n", "}" ]
// goPkg reports the import path declared in the given file's // `go_package` option. If the option is missing, goPkg returns empty string.
[ "goPkg", "reports", "the", "import", "path", "declared", "in", "the", "given", "file", "s", "go_package", "option", ".", "If", "the", "option", "is", "missing", "goPkg", "returns", "empty", "string", "." ]
54afdca5d873f7b529e2ce3def1a99df16feda90
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/regen.go#L107-L125
149,752
google/go-genproto
regen.go
protoc
func protoc(goOut string, includes, fnames []string) ([]byte, error) { args := []string{"--go_out=plugins=grpc:" + goOut} for _, inc := range includes { args = append(args, "-I", inc) } args = append(args, fnames...) return exec.Command("protoc", args...).CombinedOutput() }
go
func protoc(goOut string, includes, fnames []string) ([]byte, error) { args := []string{"--go_out=plugins=grpc:" + goOut} for _, inc := range includes { args = append(args, "-I", inc) } args = append(args, fnames...) return exec.Command("protoc", args...).CombinedOutput() }
[ "func", "protoc", "(", "goOut", "string", ",", "includes", ",", "fnames", "[", "]", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", "+", "goOut", "}", "\n", "for", "_", ",", "inc", ":=", "range", "includes", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "inc", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "fnames", "...", ")", "\n", "return", "exec", ".", "Command", "(", "\"", "\"", ",", "args", "...", ")", ".", "CombinedOutput", "(", ")", "\n", "}" ]
// protoc executes the "protoc" command on files named in fnames, // passing go_out and include flags specified in goOut and includes respectively. // protoc returns combined output from stdout and stderr.
[ "protoc", "executes", "the", "protoc", "command", "on", "files", "named", "in", "fnames", "passing", "go_out", "and", "include", "flags", "specified", "in", "goOut", "and", "includes", "respectively", ".", "protoc", "returns", "combined", "output", "from", "stdout", "and", "stderr", "." ]
54afdca5d873f7b529e2ce3def1a99df16feda90
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/regen.go#L130-L137
149,753
gopherjs/vecty
example/todomvc/store/storeutil/storeutil.go
Add
func (r *ListenerRegistry) Add(key interface{}, listener func()) { if key == nil { key = new(int) } if _, ok := r.listeners[key]; ok { panic("duplicate listener key") } r.listeners[key] = listener }
go
func (r *ListenerRegistry) Add(key interface{}, listener func()) { if key == nil { key = new(int) } if _, ok := r.listeners[key]; ok { panic("duplicate listener key") } r.listeners[key] = listener }
[ "func", "(", "r", "*", "ListenerRegistry", ")", "Add", "(", "key", "interface", "{", "}", ",", "listener", "func", "(", ")", ")", "{", "if", "key", "==", "nil", "{", "key", "=", "new", "(", "int", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "r", ".", "listeners", "[", "key", "]", ";", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "r", ".", "listeners", "[", "key", "]", "=", "listener", "\n", "}" ]
// Add adds listener with key to the registry. // key may be nil, then an arbitrary unused key is assigned. // It panics if a listener with same key is already present.
[ "Add", "adds", "listener", "with", "key", "to", "the", "registry", ".", "key", "may", "be", "nil", "then", "an", "arbitrary", "unused", "key", "is", "assigned", ".", "It", "panics", "if", "a", "listener", "with", "same", "key", "is", "already", "present", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/example/todomvc/store/storeutil/storeutil.go#L20-L28
149,754
gopherjs/vecty
dom.go
Node
func (h *HTML) Node() *js.Object { if h.node == nil { panic("vecty: cannot call (*HTML).Node() before DOM node creation / component mount") } return h.node.(wrappedObject).j }
go
func (h *HTML) Node() *js.Object { if h.node == nil { panic("vecty: cannot call (*HTML).Node() before DOM node creation / component mount") } return h.node.(wrappedObject).j }
[ "func", "(", "h", "*", "HTML", ")", "Node", "(", ")", "*", "js", ".", "Object", "{", "if", "h", ".", "node", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "h", ".", "node", ".", "(", "wrappedObject", ")", ".", "j", "\n", "}" ]
// Node returns the underlying JavaScript Element or TextNode. // // It panics if it is called before the DOM node has been attached, i.e. before // the associated component's Mounter interface would be invoked.
[ "Node", "returns", "the", "underlying", "JavaScript", "Element", "or", "TextNode", ".", "It", "panics", "if", "it", "is", "called", "before", "the", "DOM", "node", "has", "been", "attached", "i", ".", "e", ".", "before", "the", "associated", "component", "s", "Mounter", "interface", "would", "be", "invoked", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L156-L161
149,755
gopherjs/vecty
dom.go
createNode
func (h *HTML) createNode() { switch { case h.tag != "" && h.text != "": panic("vecty: internal error (only one of HTML.tag or HTML.text may be set)") case h.tag == "" && h.innerHTML != "": panic("vecty: only HTML may have UnsafeHTML attribute") case h.tag != "" && h.namespace == "": h.node = global.Get("document").Call("createElement", h.tag) case h.tag != "" && h.namespace != "": h.node = global.Get("document").Call("createElementNS", h.namespace, h.tag) default: h.node = global.Get("document").Call("createTextNode", h.text) } }
go
func (h *HTML) createNode() { switch { case h.tag != "" && h.text != "": panic("vecty: internal error (only one of HTML.tag or HTML.text may be set)") case h.tag == "" && h.innerHTML != "": panic("vecty: only HTML may have UnsafeHTML attribute") case h.tag != "" && h.namespace == "": h.node = global.Get("document").Call("createElement", h.tag) case h.tag != "" && h.namespace != "": h.node = global.Get("document").Call("createElementNS", h.namespace, h.tag) default: h.node = global.Get("document").Call("createTextNode", h.text) } }
[ "func", "(", "h", "*", "HTML", ")", "createNode", "(", ")", "{", "switch", "{", "case", "h", ".", "tag", "!=", "\"", "\"", "&&", "h", ".", "text", "!=", "\"", "\"", ":", "panic", "(", "\"", "\"", ")", "\n", "case", "h", ".", "tag", "==", "\"", "\"", "&&", "h", ".", "innerHTML", "!=", "\"", "\"", ":", "panic", "(", "\"", "\"", ")", "\n", "case", "h", ".", "tag", "!=", "\"", "\"", "&&", "h", ".", "namespace", "==", "\"", "\"", ":", "h", ".", "node", "=", "global", ".", "Get", "(", "\"", "\"", ")", ".", "Call", "(", "\"", "\"", ",", "h", ".", "tag", ")", "\n", "case", "h", ".", "tag", "!=", "\"", "\"", "&&", "h", ".", "namespace", "!=", "\"", "\"", ":", "h", ".", "node", "=", "global", ".", "Get", "(", "\"", "\"", ")", ".", "Call", "(", "\"", "\"", ",", "h", ".", "namespace", ",", "h", ".", "tag", ")", "\n", "default", ":", "h", ".", "node", "=", "global", ".", "Get", "(", "\"", "\"", ")", ".", "Call", "(", "\"", "\"", ",", "h", ".", "text", ")", "\n", "}", "\n", "}" ]
// createNode creates a HTML node of the appropriate type and namespace.
[ "createNode", "creates", "a", "HTML", "node", "of", "the", "appropriate", "type", "and", "namespace", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L175-L188
149,756
gopherjs/vecty
dom.go
reconcileText
func (h *HTML) reconcileText(prev *HTML) { h.node = prev.node // Text modifications. if h.text != prev.text { h.node.Set("nodeValue", h.text) } }
go
func (h *HTML) reconcileText(prev *HTML) { h.node = prev.node // Text modifications. if h.text != prev.text { h.node.Set("nodeValue", h.text) } }
[ "func", "(", "h", "*", "HTML", ")", "reconcileText", "(", "prev", "*", "HTML", ")", "{", "h", ".", "node", "=", "prev", ".", "node", "\n\n", "// Text modifications.", "if", "h", ".", "text", "!=", "prev", ".", "text", "{", "h", ".", "node", ".", "Set", "(", "\"", "\"", ",", "h", ".", "text", ")", "\n", "}", "\n", "}" ]
// reconcileText replaces the content of a text node.
[ "reconcileText", "replaces", "the", "content", "of", "a", "text", "node", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L191-L198
149,757
gopherjs/vecty
dom.go
removeChildren
func (h *HTML) removeChildren(prevChildren []ComponentOrHTML) { for _, prevChild := range prevChildren { if prevChildList, ok := prevChild.(KeyedList); ok { // Previous child was a list, so remove all DOM nodes in it. prevChildList.remove(h) continue } prevChildRender := extractHTML(prevChild) if prevChildRender == nil { continue } h.removeChild(prevChildRender) } }
go
func (h *HTML) removeChildren(prevChildren []ComponentOrHTML) { for _, prevChild := range prevChildren { if prevChildList, ok := prevChild.(KeyedList); ok { // Previous child was a list, so remove all DOM nodes in it. prevChildList.remove(h) continue } prevChildRender := extractHTML(prevChild) if prevChildRender == nil { continue } h.removeChild(prevChildRender) } }
[ "func", "(", "h", "*", "HTML", ")", "removeChildren", "(", "prevChildren", "[", "]", "ComponentOrHTML", ")", "{", "for", "_", ",", "prevChild", ":=", "range", "prevChildren", "{", "if", "prevChildList", ",", "ok", ":=", "prevChild", ".", "(", "KeyedList", ")", ";", "ok", "{", "// Previous child was a list, so remove all DOM nodes in it.", "prevChildList", ".", "remove", "(", "h", ")", "\n", "continue", "\n", "}", "\n", "prevChildRender", ":=", "extractHTML", "(", "prevChild", ")", "\n", "if", "prevChildRender", "==", "nil", "{", "continue", "\n", "}", "\n", "h", ".", "removeChild", "(", "prevChildRender", ")", "\n", "}", "\n", "}" ]
// removeChildren removes child elements from the previous render pass that no // longer exist on the current HTML children.
[ "removeChildren", "removes", "child", "elements", "from", "the", "previous", "render", "pass", "that", "no", "longer", "exist", "on", "the", "current", "HTML", "children", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L605-L618
149,758
gopherjs/vecty
dom.go
firstChild
func (h *HTML) firstChild() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("firstChild") }
go
func (h *HTML) firstChild() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("firstChild") }
[ "func", "(", "h", "*", "HTML", ")", "firstChild", "(", ")", "jsObject", "{", "if", "h", "==", "nil", "||", "h", ".", "node", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "h", ".", "node", ".", "Get", "(", "\"", "\"", ")", "\n", "}" ]
// firstChild returns the first child DOM node of this element.
[ "firstChild", "returns", "the", "first", "child", "DOM", "node", "of", "this", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L621-L626
149,759
gopherjs/vecty
dom.go
nextSibling
func (h *HTML) nextSibling() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("nextSibling") }
go
func (h *HTML) nextSibling() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("nextSibling") }
[ "func", "(", "h", "*", "HTML", ")", "nextSibling", "(", ")", "jsObject", "{", "if", "h", "==", "nil", "||", "h", ".", "node", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "h", ".", "node", ".", "Get", "(", "\"", "\"", ")", "\n", "}" ]
// nextSibling returns the next sibling DOM node for this element.
[ "nextSibling", "returns", "the", "next", "sibling", "DOM", "node", "for", "this", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L629-L634
149,760
gopherjs/vecty
dom.go
removeChild
func (h *HTML) removeChild(child *HTML) { // If we're removing the current insert target, use the next // sibling, if any. if h.insertBeforeNode != nil && h.insertBeforeNode == child.node { h.insertBeforeNode = h.insertBeforeNode.Get("nextSibling") } unmount(child) if child.node == nil { return } // Use the child's parent node here, in case our node is not a valid // target by the time we're called. child.node.Get("parentNode").Call("removeChild", child.node) }
go
func (h *HTML) removeChild(child *HTML) { // If we're removing the current insert target, use the next // sibling, if any. if h.insertBeforeNode != nil && h.insertBeforeNode == child.node { h.insertBeforeNode = h.insertBeforeNode.Get("nextSibling") } unmount(child) if child.node == nil { return } // Use the child's parent node here, in case our node is not a valid // target by the time we're called. child.node.Get("parentNode").Call("removeChild", child.node) }
[ "func", "(", "h", "*", "HTML", ")", "removeChild", "(", "child", "*", "HTML", ")", "{", "// If we're removing the current insert target, use the next", "// sibling, if any.", "if", "h", ".", "insertBeforeNode", "!=", "nil", "&&", "h", ".", "insertBeforeNode", "==", "child", ".", "node", "{", "h", ".", "insertBeforeNode", "=", "h", ".", "insertBeforeNode", ".", "Get", "(", "\"", "\"", ")", "\n", "}", "\n", "unmount", "(", "child", ")", "\n", "if", "child", ".", "node", "==", "nil", "{", "return", "\n", "}", "\n", "// Use the child's parent node here, in case our node is not a valid", "// target by the time we're called.", "child", ".", "node", ".", "Get", "(", "\"", "\"", ")", ".", "Call", "(", "\"", "\"", ",", "child", ".", "node", ")", "\n", "}" ]
// removeChild removes the provided child element from this element, and // triggers unmount handlers.
[ "removeChild", "removes", "the", "provided", "child", "element", "from", "this", "element", "and", "triggers", "unmount", "handlers", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L638-L651
149,761
gopherjs/vecty
dom.go
appendChild
func (h *HTML) appendChild(child *HTML) { h.node.Call("appendChild", child.node) }
go
func (h *HTML) appendChild(child *HTML) { h.node.Call("appendChild", child.node) }
[ "func", "(", "h", "*", "HTML", ")", "appendChild", "(", "child", "*", "HTML", ")", "{", "h", ".", "node", ".", "Call", "(", "\"", "\"", ",", "child", ".", "node", ")", "\n", "}" ]
// appendChild appends a new child to this element.
[ "appendChild", "appends", "a", "new", "child", "to", "this", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L654-L656
149,762
gopherjs/vecty
dom.go
insertBefore
func (h *HTML) insertBefore(node jsObject, child *HTML) { if node == nil { h.appendChild(child) return } h.node.Call("insertBefore", child.node, node) }
go
func (h *HTML) insertBefore(node jsObject, child *HTML) { if node == nil { h.appendChild(child) return } h.node.Call("insertBefore", child.node, node) }
[ "func", "(", "h", "*", "HTML", ")", "insertBefore", "(", "node", "jsObject", ",", "child", "*", "HTML", ")", "{", "if", "node", "==", "nil", "{", "h", ".", "appendChild", "(", "child", ")", "\n", "return", "\n", "}", "\n", "h", ".", "node", ".", "Call", "(", "\"", "\"", ",", "child", ".", "node", ",", "node", ")", "\n", "}" ]
// insertBefore inserts the provided child before the provided DOM node. If the // DOM node is nil, the child will be appended instead.
[ "insertBefore", "inserts", "the", "provided", "child", "before", "the", "provided", "DOM", "node", ".", "If", "the", "DOM", "node", "is", "nil", "the", "child", "will", "be", "appended", "instead", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L660-L666
149,763
gopherjs/vecty
dom.go
WithKey
func (l List) WithKey(key interface{}) KeyedList { return KeyedList{key: key, html: &HTML{children: l}} }
go
func (l List) WithKey(key interface{}) KeyedList { return KeyedList{key: key, html: &HTML{children: l}} }
[ "func", "(", "l", "List", ")", "WithKey", "(", "key", "interface", "{", "}", ")", "KeyedList", "{", "return", "KeyedList", "{", "key", ":", "key", ",", "html", ":", "&", "HTML", "{", "children", ":", "l", "}", "}", "\n", "}" ]
// WithKey wraps the List in a Keyer using the given key. List members are // inaccessible within the returned value.
[ "WithKey", "wraps", "the", "List", "in", "a", "Keyer", "using", "the", "given", "key", ".", "List", "members", "are", "inaccessible", "within", "the", "returned", "value", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L679-L681
149,764
gopherjs/vecty
dom.go
reconcile
func (l KeyedList) reconcile(parent *HTML, prevChild ComponentOrHTML) (pendingMounts []Mounter) { // Effectively become the parent (copy its scope) so that we can reconcile // our children against the prev child. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.lastRenderedChild = parent.lastRenderedChild switch v := prevChild.(type) { case KeyedList: pendingMounts = l.html.reconcileChildren(v.html) case *HTML, Component, nil: if v == nil { // No previous element, so reconcile against a parent with no // children so all of our elements are added. pendingMounts = l.html.reconcileChildren(&HTML{node: parent.node}) } else { // Build a previous render containing just the prevChild to be // replaced by this list prev := &HTML{node: parent.node, children: []ComponentOrHTML{prevChild}} if keyer, ok := prevChild.(Keyer); ok && keyer.Key() != nil { prev.keyedChildren = map[interface{}]ComponentOrHTML{keyer.Key(): prevChild} } pendingMounts = l.html.reconcileChildren(prev) } default: panic("vecty: internal error (unexpected ComponentOrHTML type " + reflect.TypeOf(v).String() + ")") } // Update the parent insertBeforeNode and lastRenderedChild values to be // ours, since we acted as the parent and ours is now updated / theirs is // outdated. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } if l.html.lastRenderedChild != nil { parent.lastRenderedChild = l.html.lastRenderedChild } return pendingMounts }
go
func (l KeyedList) reconcile(parent *HTML, prevChild ComponentOrHTML) (pendingMounts []Mounter) { // Effectively become the parent (copy its scope) so that we can reconcile // our children against the prev child. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.lastRenderedChild = parent.lastRenderedChild switch v := prevChild.(type) { case KeyedList: pendingMounts = l.html.reconcileChildren(v.html) case *HTML, Component, nil: if v == nil { // No previous element, so reconcile against a parent with no // children so all of our elements are added. pendingMounts = l.html.reconcileChildren(&HTML{node: parent.node}) } else { // Build a previous render containing just the prevChild to be // replaced by this list prev := &HTML{node: parent.node, children: []ComponentOrHTML{prevChild}} if keyer, ok := prevChild.(Keyer); ok && keyer.Key() != nil { prev.keyedChildren = map[interface{}]ComponentOrHTML{keyer.Key(): prevChild} } pendingMounts = l.html.reconcileChildren(prev) } default: panic("vecty: internal error (unexpected ComponentOrHTML type " + reflect.TypeOf(v).String() + ")") } // Update the parent insertBeforeNode and lastRenderedChild values to be // ours, since we acted as the parent and ours is now updated / theirs is // outdated. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } if l.html.lastRenderedChild != nil { parent.lastRenderedChild = l.html.lastRenderedChild } return pendingMounts }
[ "func", "(", "l", "KeyedList", ")", "reconcile", "(", "parent", "*", "HTML", ",", "prevChild", "ComponentOrHTML", ")", "(", "pendingMounts", "[", "]", "Mounter", ")", "{", "// Effectively become the parent (copy its scope) so that we can reconcile", "// our children against the prev child.", "l", ".", "html", ".", "node", "=", "parent", ".", "node", "\n", "l", ".", "html", ".", "insertBeforeNode", "=", "parent", ".", "insertBeforeNode", "\n", "l", ".", "html", ".", "lastRenderedChild", "=", "parent", ".", "lastRenderedChild", "\n\n", "switch", "v", ":=", "prevChild", ".", "(", "type", ")", "{", "case", "KeyedList", ":", "pendingMounts", "=", "l", ".", "html", ".", "reconcileChildren", "(", "v", ".", "html", ")", "\n", "case", "*", "HTML", ",", "Component", ",", "nil", ":", "if", "v", "==", "nil", "{", "// No previous element, so reconcile against a parent with no", "// children so all of our elements are added.", "pendingMounts", "=", "l", ".", "html", ".", "reconcileChildren", "(", "&", "HTML", "{", "node", ":", "parent", ".", "node", "}", ")", "\n", "}", "else", "{", "// Build a previous render containing just the prevChild to be", "// replaced by this list", "prev", ":=", "&", "HTML", "{", "node", ":", "parent", ".", "node", ",", "children", ":", "[", "]", "ComponentOrHTML", "{", "prevChild", "}", "}", "\n", "if", "keyer", ",", "ok", ":=", "prevChild", ".", "(", "Keyer", ")", ";", "ok", "&&", "keyer", ".", "Key", "(", ")", "!=", "nil", "{", "prev", ".", "keyedChildren", "=", "map", "[", "interface", "{", "}", "]", "ComponentOrHTML", "{", "keyer", ".", "Key", "(", ")", ":", "prevChild", "}", "\n", "}", "\n", "pendingMounts", "=", "l", ".", "html", ".", "reconcileChildren", "(", "prev", ")", "\n", "}", "\n", "default", ":", "panic", "(", "\"", "\"", "+", "reflect", ".", "TypeOf", "(", "v", ")", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Update the parent insertBeforeNode and lastRenderedChild values to be", "// ours, since we acted as the parent and ours is now updated / theirs is", "// outdated.", "if", "parent", ".", "insertBeforeNode", "!=", "nil", "{", "parent", ".", "insertBeforeNode", "=", "l", ".", "html", ".", "insertBeforeNode", "\n", "}", "\n", "if", "l", ".", "html", ".", "lastRenderedChild", "!=", "nil", "{", "parent", ".", "lastRenderedChild", "=", "l", ".", "html", ".", "lastRenderedChild", "\n", "}", "\n", "return", "pendingMounts", "\n", "}" ]
// reconcile reconciles the keyedList against the DOM node in a separate // context, unless keyed. Uses the currently known insertion point from the // parent to insert children at the correct position.
[ "reconcile", "reconciles", "the", "keyedList", "against", "the", "DOM", "node", "in", "a", "separate", "context", "unless", "keyed", ".", "Uses", "the", "currently", "known", "insertion", "point", "from", "the", "parent", "to", "insert", "children", "at", "the", "correct", "position", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L708-L746
149,765
gopherjs/vecty
dom.go
remove
func (l KeyedList) remove(parent *HTML) { // Become the parent so that we can remove all of our children and get an // updated insertBeforeNode value. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.removeChildren(l.html.children) // Now that the children are removed, and our insertBeforeNode value has // been updated, update the parent's insertBeforeNode value since it is now // invalid and ours is correct. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } }
go
func (l KeyedList) remove(parent *HTML) { // Become the parent so that we can remove all of our children and get an // updated insertBeforeNode value. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.removeChildren(l.html.children) // Now that the children are removed, and our insertBeforeNode value has // been updated, update the parent's insertBeforeNode value since it is now // invalid and ours is correct. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } }
[ "func", "(", "l", "KeyedList", ")", "remove", "(", "parent", "*", "HTML", ")", "{", "// Become the parent so that we can remove all of our children and get an", "// updated insertBeforeNode value.", "l", ".", "html", ".", "node", "=", "parent", ".", "node", "\n", "l", ".", "html", ".", "insertBeforeNode", "=", "parent", ".", "insertBeforeNode", "\n", "l", ".", "html", ".", "removeChildren", "(", "l", ".", "html", ".", "children", ")", "\n\n", "// Now that the children are removed, and our insertBeforeNode value has", "// been updated, update the parent's insertBeforeNode value since it is now", "// invalid and ours is correct.", "if", "parent", ".", "insertBeforeNode", "!=", "nil", "{", "parent", ".", "insertBeforeNode", "=", "l", ".", "html", ".", "insertBeforeNode", "\n", "}", "\n", "}" ]
// remove keyedList elements from the parent.
[ "remove", "keyedList", "elements", "from", "the", "parent", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L749-L762
149,766
gopherjs/vecty
dom.go
add
func (b *batchRenderer) add(c Component) { if i, ok := b.idx[c]; ok { // Shift idx for delete. for j, c := range b.batch[i+1:] { b.idx[c] = i + j } // Delete previously queued render. copy(b.batch[i:], b.batch[i+1:]) b.batch[len(b.batch)-1] = nil b.batch = b.batch[:len(b.batch)-1] } // Append and index component. b.batch = append(b.batch, c) b.idx[c] = len(b.batch) - 1 // If we're not already scheduled for a render batch, request a render on // the next frame. if !b.scheduled { b.scheduled = true requestAnimationFrame(b.render) } }
go
func (b *batchRenderer) add(c Component) { if i, ok := b.idx[c]; ok { // Shift idx for delete. for j, c := range b.batch[i+1:] { b.idx[c] = i + j } // Delete previously queued render. copy(b.batch[i:], b.batch[i+1:]) b.batch[len(b.batch)-1] = nil b.batch = b.batch[:len(b.batch)-1] } // Append and index component. b.batch = append(b.batch, c) b.idx[c] = len(b.batch) - 1 // If we're not already scheduled for a render batch, request a render on // the next frame. if !b.scheduled { b.scheduled = true requestAnimationFrame(b.render) } }
[ "func", "(", "b", "*", "batchRenderer", ")", "add", "(", "c", "Component", ")", "{", "if", "i", ",", "ok", ":=", "b", ".", "idx", "[", "c", "]", ";", "ok", "{", "// Shift idx for delete.", "for", "j", ",", "c", ":=", "range", "b", ".", "batch", "[", "i", "+", "1", ":", "]", "{", "b", ".", "idx", "[", "c", "]", "=", "i", "+", "j", "\n", "}", "\n", "// Delete previously queued render.", "copy", "(", "b", ".", "batch", "[", "i", ":", "]", ",", "b", ".", "batch", "[", "i", "+", "1", ":", "]", ")", "\n", "b", ".", "batch", "[", "len", "(", "b", ".", "batch", ")", "-", "1", "]", "=", "nil", "\n", "b", ".", "batch", "=", "b", ".", "batch", "[", ":", "len", "(", "b", ".", "batch", ")", "-", "1", "]", "\n", "}", "\n", "// Append and index component.", "b", ".", "batch", "=", "append", "(", "b", ".", "batch", ",", "c", ")", "\n", "b", ".", "idx", "[", "c", "]", "=", "len", "(", "b", ".", "batch", ")", "-", "1", "\n", "// If we're not already scheduled for a render batch, request a render on", "// the next frame.", "if", "!", "b", ".", "scheduled", "{", "b", ".", "scheduled", "=", "true", "\n", "requestAnimationFrame", "(", "b", ".", "render", ")", "\n", "}", "\n", "}" ]
// add a Component to the pending batch.
[ "add", "a", "Component", "to", "the", "pending", "batch", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L825-L845
149,767
gopherjs/vecty
dom.go
sameType
func sameType(first, second ComponentOrHTML) bool { return reflect.TypeOf(first) == reflect.TypeOf(second) }
go
func sameType(first, second ComponentOrHTML) bool { return reflect.TypeOf(first) == reflect.TypeOf(second) }
[ "func", "sameType", "(", "first", ",", "second", "ComponentOrHTML", ")", "bool", "{", "return", "reflect", ".", "TypeOf", "(", "first", ")", "==", "reflect", ".", "TypeOf", "(", "second", ")", "\n", "}" ]
// sameType returns whether first and second ComponentOrHTML are of the same // underlying type.
[ "sameType", "returns", "whether", "first", "and", "second", "ComponentOrHTML", "are", "of", "the", "same", "underlying", "type", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L915-L917
149,768
gopherjs/vecty
dom.go
copyComponent
func copyComponent(c Component) Component { if c == nil { panic("vecty: internal error (cannot copy nil Component)") } // If the Component implements the Copier interface, then use that to // perform the copy. if copier, ok := c.(Copier); ok { cpy := copier.Copy() if cpy == c { panic("vecty: Component.Copy illegally returned an identical *MyComponent pointer") } return cpy } // Component does not implement the Copier interface, so perform a shallow // copy. v := reflect.ValueOf(c) if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { panic("vecty: Component must be pointer to struct, found " + reflect.TypeOf(c).String()) } cpy := reflect.New(v.Elem().Type()) cpy.Elem().Set(v.Elem()) return cpy.Interface().(Component) }
go
func copyComponent(c Component) Component { if c == nil { panic("vecty: internal error (cannot copy nil Component)") } // If the Component implements the Copier interface, then use that to // perform the copy. if copier, ok := c.(Copier); ok { cpy := copier.Copy() if cpy == c { panic("vecty: Component.Copy illegally returned an identical *MyComponent pointer") } return cpy } // Component does not implement the Copier interface, so perform a shallow // copy. v := reflect.ValueOf(c) if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { panic("vecty: Component must be pointer to struct, found " + reflect.TypeOf(c).String()) } cpy := reflect.New(v.Elem().Type()) cpy.Elem().Set(v.Elem()) return cpy.Interface().(Component) }
[ "func", "copyComponent", "(", "c", "Component", ")", "Component", "{", "if", "c", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If the Component implements the Copier interface, then use that to", "// perform the copy.", "if", "copier", ",", "ok", ":=", "c", ".", "(", "Copier", ")", ";", "ok", "{", "cpy", ":=", "copier", ".", "Copy", "(", ")", "\n", "if", "cpy", "==", "c", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "cpy", "\n", "}", "\n\n", "// Component does not implement the Copier interface, so perform a shallow", "// copy.", "v", ":=", "reflect", ".", "ValueOf", "(", "c", ")", "\n", "if", "v", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "||", "v", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "panic", "(", "\"", "\"", "+", "reflect", ".", "TypeOf", "(", "c", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "cpy", ":=", "reflect", ".", "New", "(", "v", ".", "Elem", "(", ")", ".", "Type", "(", ")", ")", "\n", "cpy", ".", "Elem", "(", ")", ".", "Set", "(", "v", ".", "Elem", "(", ")", ")", "\n", "return", "cpy", ".", "Interface", "(", ")", ".", "(", "Component", ")", "\n", "}" ]
// copyComponent makes a copy of the given component.
[ "copyComponent", "makes", "a", "copy", "of", "the", "given", "component", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L920-L944
149,769
gopherjs/vecty
dom.go
mountUnmount
func mountUnmount(next, prev ComponentOrHTML) Mounter { if next == prev { return nil } if !sameType(next, prev) { if prev != nil { unmount(prev) } if m, ok := next.(Mounter); ok { return m } return nil } if prevHTML := extractHTML(prev); prevHTML != nil { if nextHTML := extractHTML(next); nextHTML == nil || prevHTML.node != nextHTML.node { for _, child := range prevHTML.children { unmount(child) } } } if u, ok := prev.(Unmounter); ok { u.Unmount() } if m, ok := next.(Mounter); ok { return m } return nil }
go
func mountUnmount(next, prev ComponentOrHTML) Mounter { if next == prev { return nil } if !sameType(next, prev) { if prev != nil { unmount(prev) } if m, ok := next.(Mounter); ok { return m } return nil } if prevHTML := extractHTML(prev); prevHTML != nil { if nextHTML := extractHTML(next); nextHTML == nil || prevHTML.node != nextHTML.node { for _, child := range prevHTML.children { unmount(child) } } } if u, ok := prev.(Unmounter); ok { u.Unmount() } if m, ok := next.(Mounter); ok { return m } return nil }
[ "func", "mountUnmount", "(", "next", ",", "prev", "ComponentOrHTML", ")", "Mounter", "{", "if", "next", "==", "prev", "{", "return", "nil", "\n", "}", "\n", "if", "!", "sameType", "(", "next", ",", "prev", ")", "{", "if", "prev", "!=", "nil", "{", "unmount", "(", "prev", ")", "\n", "}", "\n", "if", "m", ",", "ok", ":=", "next", ".", "(", "Mounter", ")", ";", "ok", "{", "return", "m", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "prevHTML", ":=", "extractHTML", "(", "prev", ")", ";", "prevHTML", "!=", "nil", "{", "if", "nextHTML", ":=", "extractHTML", "(", "next", ")", ";", "nextHTML", "==", "nil", "||", "prevHTML", ".", "node", "!=", "nextHTML", ".", "node", "{", "for", "_", ",", "child", ":=", "range", "prevHTML", ".", "children", "{", "unmount", "(", "child", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "u", ",", "ok", ":=", "prev", ".", "(", "Unmounter", ")", ";", "ok", "{", "u", ".", "Unmount", "(", ")", "\n", "}", "\n", "if", "m", ",", "ok", ":=", "next", ".", "(", "Mounter", ")", ";", "ok", "{", "return", "m", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mountUnmount determines whether a mount or unmount event should occur, // actions unmounts recursively if appropriate, and returns either a Mounter, // or nil.
[ "mountUnmount", "determines", "whether", "a", "mount", "or", "unmount", "event", "should", "occur", "actions", "unmounts", "recursively", "if", "appropriate", "and", "returns", "either", "a", "Mounter", "or", "nil", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1076-L1103
149,770
gopherjs/vecty
dom.go
mount
func mount(pendingMounts ...Mounter) { for _, mounter := range pendingMounts { if mounter == nil { continue } if c, ok := mounter.(Component); ok { if c.Context().mounted { continue } c.Context().mounted = true c.Context().unmounted = false } mounter.Mount() } }
go
func mount(pendingMounts ...Mounter) { for _, mounter := range pendingMounts { if mounter == nil { continue } if c, ok := mounter.(Component); ok { if c.Context().mounted { continue } c.Context().mounted = true c.Context().unmounted = false } mounter.Mount() } }
[ "func", "mount", "(", "pendingMounts", "...", "Mounter", ")", "{", "for", "_", ",", "mounter", ":=", "range", "pendingMounts", "{", "if", "mounter", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "c", ",", "ok", ":=", "mounter", ".", "(", "Component", ")", ";", "ok", "{", "if", "c", ".", "Context", "(", ")", ".", "mounted", "{", "continue", "\n", "}", "\n", "c", ".", "Context", "(", ")", ".", "mounted", "=", "true", "\n", "c", ".", "Context", "(", ")", ".", "unmounted", "=", "false", "\n", "}", "\n", "mounter", ".", "Mount", "(", ")", "\n", "}", "\n", "}" ]
// mount all pending Mounters
[ "mount", "all", "pending", "Mounters" ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1106-L1120
149,771
gopherjs/vecty
dom.go
unmount
func unmount(e ComponentOrHTML) { if c, ok := e.(Component); ok { if c.Context().unmounted { return } c.Context().unmounted = true c.Context().mounted = false if prevRenderComponent, ok := c.Context().prevRender.(Component); ok { unmount(prevRenderComponent) } } if l, ok := e.(KeyedList); ok { for _, child := range l.html.children { unmount(child) } return } if h := extractHTML(e); h != nil { for _, child := range h.children { unmount(child) } } if u, ok := e.(Unmounter); ok { u.Unmount() } }
go
func unmount(e ComponentOrHTML) { if c, ok := e.(Component); ok { if c.Context().unmounted { return } c.Context().unmounted = true c.Context().mounted = false if prevRenderComponent, ok := c.Context().prevRender.(Component); ok { unmount(prevRenderComponent) } } if l, ok := e.(KeyedList); ok { for _, child := range l.html.children { unmount(child) } return } if h := extractHTML(e); h != nil { for _, child := range h.children { unmount(child) } } if u, ok := e.(Unmounter); ok { u.Unmount() } }
[ "func", "unmount", "(", "e", "ComponentOrHTML", ")", "{", "if", "c", ",", "ok", ":=", "e", ".", "(", "Component", ")", ";", "ok", "{", "if", "c", ".", "Context", "(", ")", ".", "unmounted", "{", "return", "\n", "}", "\n", "c", ".", "Context", "(", ")", ".", "unmounted", "=", "true", "\n", "c", ".", "Context", "(", ")", ".", "mounted", "=", "false", "\n", "if", "prevRenderComponent", ",", "ok", ":=", "c", ".", "Context", "(", ")", ".", "prevRender", ".", "(", "Component", ")", ";", "ok", "{", "unmount", "(", "prevRenderComponent", ")", "\n", "}", "\n", "}", "\n\n", "if", "l", ",", "ok", ":=", "e", ".", "(", "KeyedList", ")", ";", "ok", "{", "for", "_", ",", "child", ":=", "range", "l", ".", "html", ".", "children", "{", "unmount", "(", "child", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "if", "h", ":=", "extractHTML", "(", "e", ")", ";", "h", "!=", "nil", "{", "for", "_", ",", "child", ":=", "range", "h", ".", "children", "{", "unmount", "(", "child", ")", "\n", "}", "\n", "}", "\n\n", "if", "u", ",", "ok", ":=", "e", ".", "(", "Unmounter", ")", ";", "ok", "{", "u", ".", "Unmount", "(", ")", "\n", "}", "\n", "}" ]
// unmount recursively unmounts the provided ComponentOrHTML, and any children // that satisfy the Unmounter interface.
[ "unmount", "recursively", "unmounts", "the", "provided", "ComponentOrHTML", "and", "any", "children", "that", "satisfy", "the", "Unmounter", "interface", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1124-L1152
149,772
gopherjs/vecty
dom.go
RenderBody
func RenderBody(body Component) { // block batch until we're done batch.scheduled = true defer func() { requestAnimationFrame(batch.render) }() nextRender, skip, pendingMounts := renderComponent(body, nil) if skip { panic("vecty: RenderBody Component.SkipRender illegally returned true") } if nextRender.tag != "body" { panic("vecty: RenderBody expected Component.Render to return a body tag, found \"" + nextRender.tag + "\"") } doc := global.Get("document") if doc.Get("readyState").String() == "loading" { doc.Call("addEventListener", "DOMContentLoaded", func() { // avoid duplicate body doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }) return } doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }
go
func RenderBody(body Component) { // block batch until we're done batch.scheduled = true defer func() { requestAnimationFrame(batch.render) }() nextRender, skip, pendingMounts := renderComponent(body, nil) if skip { panic("vecty: RenderBody Component.SkipRender illegally returned true") } if nextRender.tag != "body" { panic("vecty: RenderBody expected Component.Render to return a body tag, found \"" + nextRender.tag + "\"") } doc := global.Get("document") if doc.Get("readyState").String() == "loading" { doc.Call("addEventListener", "DOMContentLoaded", func() { // avoid duplicate body doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }) return } doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }
[ "func", "RenderBody", "(", "body", "Component", ")", "{", "// block batch until we're done", "batch", ".", "scheduled", "=", "true", "\n", "defer", "func", "(", ")", "{", "requestAnimationFrame", "(", "batch", ".", "render", ")", "\n", "}", "(", ")", "\n", "nextRender", ",", "skip", ",", "pendingMounts", ":=", "renderComponent", "(", "body", ",", "nil", ")", "\n", "if", "skip", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "nextRender", ".", "tag", "!=", "\"", "\"", "{", "panic", "(", "\"", "\\\"", "\"", "+", "nextRender", ".", "tag", "+", "\"", "\\\"", "\"", ")", "\n", "}", "\n", "doc", ":=", "global", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "doc", ".", "Get", "(", "\"", "\"", ")", ".", "String", "(", ")", "==", "\"", "\"", "{", "doc", ".", "Call", "(", "\"", "\"", ",", "\"", "\"", ",", "func", "(", ")", "{", "// avoid duplicate body", "doc", ".", "Set", "(", "\"", "\"", ",", "nextRender", ".", "node", ")", "\n", "mount", "(", "pendingMounts", "...", ")", "\n", "if", "m", ",", "ok", ":=", "body", ".", "(", "Mounter", ")", ";", "ok", "{", "mount", "(", "m", ")", "\n", "}", "\n", "}", ")", "\n", "return", "\n", "}", "\n", "doc", ".", "Set", "(", "\"", "\"", ",", "nextRender", ".", "node", ")", "\n", "mount", "(", "pendingMounts", "...", ")", "\n", "if", "m", ",", "ok", ":=", "body", ".", "(", "Mounter", ")", ";", "ok", "{", "mount", "(", "m", ")", "\n", "}", "\n", "}" ]
// RenderBody renders the given component as the document body. The given // Component's Render method must return a "body" element.
[ "RenderBody", "renders", "the", "given", "component", "as", "the", "document", "body", ".", "The", "given", "Component", "s", "Render", "method", "must", "return", "a", "body", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1161-L1190
149,773
gopherjs/vecty
dom.go
AddStylesheet
func AddStylesheet(url string) { link := global.Get("document").Call("createElement", "link") link.Set("rel", "stylesheet") link.Set("href", url) global.Get("document").Get("head").Call("appendChild", link) }
go
func AddStylesheet(url string) { link := global.Get("document").Call("createElement", "link") link.Set("rel", "stylesheet") link.Set("href", url) global.Get("document").Get("head").Call("appendChild", link) }
[ "func", "AddStylesheet", "(", "url", "string", ")", "{", "link", ":=", "global", ".", "Get", "(", "\"", "\"", ")", ".", "Call", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "link", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "link", ".", "Set", "(", "\"", "\"", ",", "url", ")", "\n", "global", ".", "Get", "(", "\"", "\"", ")", ".", "Get", "(", "\"", "\"", ")", ".", "Call", "(", "\"", "\"", ",", "link", ")", "\n", "}" ]
// AddStylesheet adds an external stylesheet to the document.
[ "AddStylesheet", "adds", "an", "external", "stylesheet", "to", "the", "document", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1198-L1203
149,774
gopherjs/vecty
markup.go
Data
func Data(key, value string) Applyer { return markupFunc(func(h *HTML) { if h.dataset == nil { h.dataset = make(map[string]string) } h.dataset[key] = value }) }
go
func Data(key, value string) Applyer { return markupFunc(func(h *HTML) { if h.dataset == nil { h.dataset = make(map[string]string) } h.dataset[key] = value }) }
[ "func", "Data", "(", "key", ",", "value", "string", ")", "Applyer", "{", "return", "markupFunc", "(", "func", "(", "h", "*", "HTML", ")", "{", "if", "h", ".", "dataset", "==", "nil", "{", "h", ".", "dataset", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "h", ".", "dataset", "[", "key", "]", "=", "value", "\n", "}", ")", "\n", "}" ]
// Data returns an Applyer which applies the given data attribute.
[ "Data", "returns", "an", "Applyer", "which", "applies", "the", "given", "data", "attribute", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L140-L147
149,775
gopherjs/vecty
markup.go
Class
func Class(class ...string) Applyer { mustValidateClassNames(class) return markupFunc(func(h *HTML) { if h.classes == nil { h.classes = make(map[string]struct{}) } for _, name := range class { h.classes[name] = struct{}{} } }) }
go
func Class(class ...string) Applyer { mustValidateClassNames(class) return markupFunc(func(h *HTML) { if h.classes == nil { h.classes = make(map[string]struct{}) } for _, name := range class { h.classes[name] = struct{}{} } }) }
[ "func", "Class", "(", "class", "...", "string", ")", "Applyer", "{", "mustValidateClassNames", "(", "class", ")", "\n", "return", "markupFunc", "(", "func", "(", "h", "*", "HTML", ")", "{", "if", "h", ".", "classes", "==", "nil", "{", "h", ".", "classes", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "class", "{", "h", ".", "classes", "[", "name", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Class returns an Applyer which applies the provided classes. Subsequent // calls to this function will append additional classes. To toggle classes, // use ClassMap instead. Each class name must be passed as a separate argument.
[ "Class", "returns", "an", "Applyer", "which", "applies", "the", "provided", "classes", ".", "Subsequent", "calls", "to", "this", "function", "will", "append", "additional", "classes", ".", "To", "toggle", "classes", "use", "ClassMap", "instead", ".", "Each", "class", "name", "must", "be", "passed", "as", "a", "separate", "argument", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L152-L162
149,776
gopherjs/vecty
markup.go
mustValidateClassNames
func mustValidateClassNames(class []string) { for _, name := range class { if containsSpace(name) { panic(`vecty: invalid argument to vecty.Class "` + name + `" (string may not contain spaces)`) } } }
go
func mustValidateClassNames(class []string) { for _, name := range class { if containsSpace(name) { panic(`vecty: invalid argument to vecty.Class "` + name + `" (string may not contain spaces)`) } } }
[ "func", "mustValidateClassNames", "(", "class", "[", "]", "string", ")", "{", "for", "_", ",", "name", ":=", "range", "class", "{", "if", "containsSpace", "(", "name", ")", "{", "panic", "(", "`vecty: invalid argument to vecty.Class \"`", "+", "name", "+", "`\" (string may not contain spaces)`", ")", "\n", "}", "\n", "}", "\n", "}" ]
// mustValidateClassNames ensures no class names have spaces // and panics with clear instructions on how to fix this user error.
[ "mustValidateClassNames", "ensures", "no", "class", "names", "have", "spaces", "and", "panics", "with", "clear", "instructions", "on", "how", "to", "fix", "this", "user", "error", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L166-L172
149,777
gopherjs/vecty
markup.go
containsSpace
func containsSpace(s string) bool { for _, c := range s { if c == ' ' { return true } } return false }
go
func containsSpace(s string) bool { for _, c := range s { if c == ' ' { return true } } return false }
[ "func", "containsSpace", "(", "s", "string", ")", "bool", "{", "for", "_", ",", "c", ":=", "range", "s", "{", "if", "c", "==", "' '", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// containsSpace reports whether s contains a space character.
[ "containsSpace", "reports", "whether", "s", "contains", "a", "space", "character", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L175-L182
149,778
gopherjs/vecty
markup.go
If
func If(cond bool, children ...ComponentOrHTML) MarkupOrChild { if cond { return List(children) } return nil }
go
func If(cond bool, children ...ComponentOrHTML) MarkupOrChild { if cond { return List(children) } return nil }
[ "func", "If", "(", "cond", "bool", ",", "children", "...", "ComponentOrHTML", ")", "MarkupOrChild", "{", "if", "cond", "{", "return", "List", "(", "children", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// If returns nil if cond is false, otherwise it returns the given children.
[ "If", "returns", "nil", "if", "cond", "is", "false", "otherwise", "it", "returns", "the", "given", "children", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L234-L239
149,779
gopherjs/vecty
markup.go
MarkupIf
func MarkupIf(cond bool, markup ...Applyer) Applyer { if cond { return Markup(markup...) } return nil }
go
func MarkupIf(cond bool, markup ...Applyer) Applyer { if cond { return Markup(markup...) } return nil }
[ "func", "MarkupIf", "(", "cond", "bool", ",", "markup", "...", "Applyer", ")", "Applyer", "{", "if", "cond", "{", "return", "Markup", "(", "markup", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MarkupIf returns nil if cond is false, otherwise it returns the given markup.
[ "MarkupIf", "returns", "nil", "if", "cond", "is", "false", "otherwise", "it", "returns", "the", "given", "markup", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L242-L247
149,780
gopherjs/vecty
example/todomvc/dispatcher/dispatcher.go
Register
func Register(callback func(action interface{})) ID { idCounter++ id := idCounter callbacks[id] = callback return id }
go
func Register(callback func(action interface{})) ID { idCounter++ id := idCounter callbacks[id] = callback return id }
[ "func", "Register", "(", "callback", "func", "(", "action", "interface", "{", "}", ")", ")", "ID", "{", "idCounter", "++", "\n", "id", ":=", "idCounter", "\n", "callbacks", "[", "id", "]", "=", "callback", "\n", "return", "id", "\n", "}" ]
// Register registers the callback to handle dispatched actions, the returned // ID may be used to unregister the callback later.
[ "Register", "registers", "the", "callback", "to", "handle", "dispatched", "actions", "the", "returned", "ID", "may", "be", "used", "to", "unregister", "the", "callback", "later", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/example/todomvc/dispatcher/dispatcher.go#L18-L23
149,781
dghubble/go-twitter
twitter/twitter.go
Bool
func Bool(v bool) *bool { ptr := new(bool) *ptr = v return ptr }
go
func Bool(v bool) *bool { ptr := new(bool) *ptr = v return ptr }
[ "func", "Bool", "(", "v", "bool", ")", "*", "bool", "{", "ptr", ":=", "new", "(", "bool", ")", "\n", "*", "ptr", "=", "v", "\n", "return", "ptr", "\n", "}" ]
// Bool returns a new pointer to the given bool value.
[ "Bool", "returns", "a", "new", "pointer", "to", "the", "given", "bool", "value", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/twitter.go#L54-L58
149,782
dghubble/go-twitter
twitter/twitter.go
Float
func Float(v float64) *float64 { ptr := new(float64) *ptr = v return ptr }
go
func Float(v float64) *float64 { ptr := new(float64) *ptr = v return ptr }
[ "func", "Float", "(", "v", "float64", ")", "*", "float64", "{", "ptr", ":=", "new", "(", "float64", ")", "\n", "*", "ptr", "=", "v", "\n", "return", "ptr", "\n", "}" ]
// Float returns a new pointer to the given float64 value.
[ "Float", "returns", "a", "new", "pointer", "to", "the", "given", "float64", "value", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/twitter.go#L61-L65
149,783
dghubble/go-twitter
twitter/demux.go
NewSwitchDemux
func NewSwitchDemux() SwitchDemux { return SwitchDemux{ All: func(message interface{}) {}, Tweet: func(tweet *Tweet) {}, DM: func(dm *DirectMessage) {}, StatusDeletion: func(deletion *StatusDeletion) {}, LocationDeletion: func(LocationDeletion *LocationDeletion) {}, StreamLimit: func(limit *StreamLimit) {}, StatusWithheld: func(statusWithheld *StatusWithheld) {}, UserWithheld: func(userWithheld *UserWithheld) {}, StreamDisconnect: func(disconnect *StreamDisconnect) {}, Warning: func(warning *StallWarning) {}, FriendsList: func(friendsList *FriendsList) {}, Event: func(event *Event) {}, Other: func(message interface{}) {}, } }
go
func NewSwitchDemux() SwitchDemux { return SwitchDemux{ All: func(message interface{}) {}, Tweet: func(tweet *Tweet) {}, DM: func(dm *DirectMessage) {}, StatusDeletion: func(deletion *StatusDeletion) {}, LocationDeletion: func(LocationDeletion *LocationDeletion) {}, StreamLimit: func(limit *StreamLimit) {}, StatusWithheld: func(statusWithheld *StatusWithheld) {}, UserWithheld: func(userWithheld *UserWithheld) {}, StreamDisconnect: func(disconnect *StreamDisconnect) {}, Warning: func(warning *StallWarning) {}, FriendsList: func(friendsList *FriendsList) {}, Event: func(event *Event) {}, Other: func(message interface{}) {}, } }
[ "func", "NewSwitchDemux", "(", ")", "SwitchDemux", "{", "return", "SwitchDemux", "{", "All", ":", "func", "(", "message", "interface", "{", "}", ")", "{", "}", ",", "Tweet", ":", "func", "(", "tweet", "*", "Tweet", ")", "{", "}", ",", "DM", ":", "func", "(", "dm", "*", "DirectMessage", ")", "{", "}", ",", "StatusDeletion", ":", "func", "(", "deletion", "*", "StatusDeletion", ")", "{", "}", ",", "LocationDeletion", ":", "func", "(", "LocationDeletion", "*", "LocationDeletion", ")", "{", "}", ",", "StreamLimit", ":", "func", "(", "limit", "*", "StreamLimit", ")", "{", "}", ",", "StatusWithheld", ":", "func", "(", "statusWithheld", "*", "StatusWithheld", ")", "{", "}", ",", "UserWithheld", ":", "func", "(", "userWithheld", "*", "UserWithheld", ")", "{", "}", ",", "StreamDisconnect", ":", "func", "(", "disconnect", "*", "StreamDisconnect", ")", "{", "}", ",", "Warning", ":", "func", "(", "warning", "*", "StallWarning", ")", "{", "}", ",", "FriendsList", ":", "func", "(", "friendsList", "*", "FriendsList", ")", "{", "}", ",", "Event", ":", "func", "(", "event", "*", "Event", ")", "{", "}", ",", "Other", ":", "func", "(", "message", "interface", "{", "}", ")", "{", "}", ",", "}", "\n", "}" ]
// NewSwitchDemux returns a new SwitchMux which has NoOp handler functions.
[ "NewSwitchDemux", "returns", "a", "new", "SwitchMux", "which", "has", "NoOp", "handler", "functions", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/demux.go#L30-L46
149,784
dghubble/go-twitter
twitter/demux.go
Handle
func (d SwitchDemux) Handle(message interface{}) { d.All(message) switch msg := message.(type) { case *Tweet: d.Tweet(msg) case *DirectMessage: d.DM(msg) case *StatusDeletion: d.StatusDeletion(msg) case *LocationDeletion: d.LocationDeletion(msg) case *StreamLimit: d.StreamLimit(msg) case *StatusWithheld: d.StatusWithheld(msg) case *UserWithheld: d.UserWithheld(msg) case *StreamDisconnect: d.StreamDisconnect(msg) case *StallWarning: d.Warning(msg) case *FriendsList: d.FriendsList(msg) case *Event: d.Event(msg) default: d.Other(msg) } }
go
func (d SwitchDemux) Handle(message interface{}) { d.All(message) switch msg := message.(type) { case *Tweet: d.Tweet(msg) case *DirectMessage: d.DM(msg) case *StatusDeletion: d.StatusDeletion(msg) case *LocationDeletion: d.LocationDeletion(msg) case *StreamLimit: d.StreamLimit(msg) case *StatusWithheld: d.StatusWithheld(msg) case *UserWithheld: d.UserWithheld(msg) case *StreamDisconnect: d.StreamDisconnect(msg) case *StallWarning: d.Warning(msg) case *FriendsList: d.FriendsList(msg) case *Event: d.Event(msg) default: d.Other(msg) } }
[ "func", "(", "d", "SwitchDemux", ")", "Handle", "(", "message", "interface", "{", "}", ")", "{", "d", ".", "All", "(", "message", ")", "\n", "switch", "msg", ":=", "message", ".", "(", "type", ")", "{", "case", "*", "Tweet", ":", "d", ".", "Tweet", "(", "msg", ")", "\n", "case", "*", "DirectMessage", ":", "d", ".", "DM", "(", "msg", ")", "\n", "case", "*", "StatusDeletion", ":", "d", ".", "StatusDeletion", "(", "msg", ")", "\n", "case", "*", "LocationDeletion", ":", "d", ".", "LocationDeletion", "(", "msg", ")", "\n", "case", "*", "StreamLimit", ":", "d", ".", "StreamLimit", "(", "msg", ")", "\n", "case", "*", "StatusWithheld", ":", "d", ".", "StatusWithheld", "(", "msg", ")", "\n", "case", "*", "UserWithheld", ":", "d", ".", "UserWithheld", "(", "msg", ")", "\n", "case", "*", "StreamDisconnect", ":", "d", ".", "StreamDisconnect", "(", "msg", ")", "\n", "case", "*", "StallWarning", ":", "d", ".", "Warning", "(", "msg", ")", "\n", "case", "*", "FriendsList", ":", "d", ".", "FriendsList", "(", "msg", ")", "\n", "case", "*", "Event", ":", "d", ".", "Event", "(", "msg", ")", "\n", "default", ":", "d", ".", "Other", "(", "msg", ")", "\n", "}", "\n", "}" ]
// Handle determines the type of a message and calls the corresponding receiver // function with the typed message. All messages are passed to the All func. // Messages with unmatched types are passed to the Other func.
[ "Handle", "determines", "the", "type", "of", "a", "message", "and", "calls", "the", "corresponding", "receiver", "function", "with", "the", "typed", "message", ".", "All", "messages", "are", "passed", "to", "the", "All", "func", ".", "Messages", "with", "unmatched", "types", "are", "passed", "to", "the", "Other", "func", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/demux.go#L51-L79
149,785
dghubble/go-twitter
twitter/streams.go
newStreamService
func newStreamService(client *http.Client, sling *sling.Sling) *StreamService { sling.Set("User-Agent", userAgent) return &StreamService{ client: client, public: sling.New().Base(publicStream).Path("statuses/"), user: sling.New().Base(userStream), site: sling.New().Base(siteStream), } }
go
func newStreamService(client *http.Client, sling *sling.Sling) *StreamService { sling.Set("User-Agent", userAgent) return &StreamService{ client: client, public: sling.New().Base(publicStream).Path("statuses/"), user: sling.New().Base(userStream), site: sling.New().Base(siteStream), } }
[ "func", "newStreamService", "(", "client", "*", "http", ".", "Client", ",", "sling", "*", "sling", ".", "Sling", ")", "*", "StreamService", "{", "sling", ".", "Set", "(", "\"", "\"", ",", "userAgent", ")", "\n", "return", "&", "StreamService", "{", "client", ":", "client", ",", "public", ":", "sling", ".", "New", "(", ")", ".", "Base", "(", "publicStream", ")", ".", "Path", "(", "\"", "\"", ")", ",", "user", ":", "sling", ".", "New", "(", ")", ".", "Base", "(", "userStream", ")", ",", "site", ":", "sling", ".", "New", "(", ")", ".", "Base", "(", "siteStream", ")", ",", "}", "\n", "}" ]
// newStreamService returns a new StreamService.
[ "newStreamService", "returns", "a", "new", "StreamService", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L30-L38
149,786
dghubble/go-twitter
twitter/streams.go
Stop
func (s *Stream) Stop() { close(s.done) // Scanner does not have a Stop() or take a done channel, so for low volume // streams Scan() blocks until the next keep-alive. Close the resp.Body to // escape and stop the stream in a timely fashion. if s.body != nil { s.body.Close() } // block until the retry goroutine stops s.group.Wait() }
go
func (s *Stream) Stop() { close(s.done) // Scanner does not have a Stop() or take a done channel, so for low volume // streams Scan() blocks until the next keep-alive. Close the resp.Body to // escape and stop the stream in a timely fashion. if s.body != nil { s.body.Close() } // block until the retry goroutine stops s.group.Wait() }
[ "func", "(", "s", "*", "Stream", ")", "Stop", "(", ")", "{", "close", "(", "s", ".", "done", ")", "\n", "// Scanner does not have a Stop() or take a done channel, so for low volume", "// streams Scan() blocks until the next keep-alive. Close the resp.Body to", "// escape and stop the stream in a timely fashion.", "if", "s", ".", "body", "!=", "nil", "{", "s", ".", "body", ".", "Close", "(", ")", "\n", "}", "\n", "// block until the retry goroutine stops", "s", ".", "group", ".", "Wait", "(", ")", "\n", "}" ]
// Stop signals retry and receiver to stop, closes the Messages channel, and // blocks until done.
[ "Stop", "signals", "retry", "and", "receiver", "to", "stop", "closes", "the", "Messages", "channel", "and", "blocks", "until", "done", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L169-L179
149,787
dghubble/go-twitter
twitter/streams.go
receive
func (s *Stream) receive(body io.Reader) { reader := newStreamResponseBodyReader(body) for !stopped(s.done) { data, err := reader.readNext() if err != nil { return } if len(data) == 0 { // empty keep-alive continue } select { // send messages, data, or errors case s.Messages <- getMessage(data): continue // allow client to Stop(), even if not receiving case <-s.done: return } } }
go
func (s *Stream) receive(body io.Reader) { reader := newStreamResponseBodyReader(body) for !stopped(s.done) { data, err := reader.readNext() if err != nil { return } if len(data) == 0 { // empty keep-alive continue } select { // send messages, data, or errors case s.Messages <- getMessage(data): continue // allow client to Stop(), even if not receiving case <-s.done: return } } }
[ "func", "(", "s", "*", "Stream", ")", "receive", "(", "body", "io", ".", "Reader", ")", "{", "reader", ":=", "newStreamResponseBodyReader", "(", "body", ")", "\n", "for", "!", "stopped", "(", "s", ".", "done", ")", "{", "data", ",", "err", ":=", "reader", ".", "readNext", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "len", "(", "data", ")", "==", "0", "{", "// empty keep-alive", "continue", "\n", "}", "\n", "select", "{", "// send messages, data, or errors", "case", "s", ".", "Messages", "<-", "getMessage", "(", "data", ")", ":", "continue", "\n", "// allow client to Stop(), even if not receiving", "case", "<-", "s", ".", "done", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// receive scans a stream response body, JSON decodes tokens to messages, and // sends messages to the Messages channel. Receiving continues until an EOF, // scan error, or the done channel is closed.
[ "receive", "scans", "a", "stream", "response", "body", "JSON", "decodes", "tokens", "to", "messages", "and", "sends", "messages", "to", "the", "Messages", "channel", ".", "Receiving", "continues", "until", "an", "EOF", "scan", "error", "or", "the", "done", "channel", "is", "closed", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L230-L250
149,788
dghubble/go-twitter
twitter/streams.go
decodeMessage
func decodeMessage(token []byte, data map[string]interface{}) interface{} { if hasPath(data, "retweet_count") { tweet := new(Tweet) json.Unmarshal(token, tweet) return tweet } else if hasPath(data, "direct_message") { notice := new(directMessageNotice) json.Unmarshal(token, notice) return notice.DirectMessage } else if hasPath(data, "delete") { notice := new(statusDeletionNotice) json.Unmarshal(token, notice) return notice.Delete.StatusDeletion } else if hasPath(data, "scrub_geo") { notice := new(locationDeletionNotice) json.Unmarshal(token, notice) return notice.ScrubGeo } else if hasPath(data, "limit") { notice := new(streamLimitNotice) json.Unmarshal(token, notice) return notice.Limit } else if hasPath(data, "status_withheld") { notice := new(statusWithheldNotice) json.Unmarshal(token, notice) return notice.StatusWithheld } else if hasPath(data, "user_withheld") { notice := new(userWithheldNotice) json.Unmarshal(token, notice) return notice.UserWithheld } else if hasPath(data, "disconnect") { notice := new(streamDisconnectNotice) json.Unmarshal(token, notice) return notice.StreamDisconnect } else if hasPath(data, "warning") { notice := new(stallWarningNotice) json.Unmarshal(token, notice) return notice.StallWarning } else if hasPath(data, "friends") { friendsList := new(FriendsList) json.Unmarshal(token, friendsList) return friendsList } else if hasPath(data, "event") { event := new(Event) json.Unmarshal(token, event) return event } // message type unknown, return the data map[string]interface{} return data }
go
func decodeMessage(token []byte, data map[string]interface{}) interface{} { if hasPath(data, "retweet_count") { tweet := new(Tweet) json.Unmarshal(token, tweet) return tweet } else if hasPath(data, "direct_message") { notice := new(directMessageNotice) json.Unmarshal(token, notice) return notice.DirectMessage } else if hasPath(data, "delete") { notice := new(statusDeletionNotice) json.Unmarshal(token, notice) return notice.Delete.StatusDeletion } else if hasPath(data, "scrub_geo") { notice := new(locationDeletionNotice) json.Unmarshal(token, notice) return notice.ScrubGeo } else if hasPath(data, "limit") { notice := new(streamLimitNotice) json.Unmarshal(token, notice) return notice.Limit } else if hasPath(data, "status_withheld") { notice := new(statusWithheldNotice) json.Unmarshal(token, notice) return notice.StatusWithheld } else if hasPath(data, "user_withheld") { notice := new(userWithheldNotice) json.Unmarshal(token, notice) return notice.UserWithheld } else if hasPath(data, "disconnect") { notice := new(streamDisconnectNotice) json.Unmarshal(token, notice) return notice.StreamDisconnect } else if hasPath(data, "warning") { notice := new(stallWarningNotice) json.Unmarshal(token, notice) return notice.StallWarning } else if hasPath(data, "friends") { friendsList := new(FriendsList) json.Unmarshal(token, friendsList) return friendsList } else if hasPath(data, "event") { event := new(Event) json.Unmarshal(token, event) return event } // message type unknown, return the data map[string]interface{} return data }
[ "func", "decodeMessage", "(", "token", "[", "]", "byte", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "tweet", ":=", "new", "(", "Tweet", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "tweet", ")", "\n", "return", "tweet", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "directMessageNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "DirectMessage", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "statusDeletionNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "Delete", ".", "StatusDeletion", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "locationDeletionNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "ScrubGeo", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "streamLimitNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "Limit", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "statusWithheldNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "StatusWithheld", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "userWithheldNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "UserWithheld", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "streamDisconnectNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "StreamDisconnect", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "notice", ":=", "new", "(", "stallWarningNotice", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "notice", ")", "\n", "return", "notice", ".", "StallWarning", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "friendsList", ":=", "new", "(", "FriendsList", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "friendsList", ")", "\n", "return", "friendsList", "\n", "}", "else", "if", "hasPath", "(", "data", ",", "\"", "\"", ")", "{", "event", ":=", "new", "(", "Event", ")", "\n", "json", ".", "Unmarshal", "(", "token", ",", "event", ")", "\n", "return", "event", "\n", "}", "\n", "// message type unknown, return the data map[string]interface{}", "return", "data", "\n", "}" ]
// decodeMessage determines the message type from known data keys, allocates // at most one message struct, and JSON decodes the token into the message. // Returns the message struct or the data map if the message type could not be // determined.
[ "decodeMessage", "determines", "the", "message", "type", "from", "known", "data", "keys", "allocates", "at", "most", "one", "message", "struct", "and", "JSON", "decodes", "the", "token", "into", "the", "message", ".", "Returns", "the", "message", "struct", "or", "the", "data", "map", "if", "the", "message", "type", "could", "not", "be", "determined", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L269-L317
149,789
dghubble/go-twitter
twitter/streams.go
hasPath
func hasPath(data map[string]interface{}, key string) bool { _, ok := data[key] return ok }
go
func hasPath(data map[string]interface{}, key string) bool { _, ok := data[key] return ok }
[ "func", "hasPath", "(", "data", "map", "[", "string", "]", "interface", "{", "}", ",", "key", "string", ")", "bool", "{", "_", ",", "ok", ":=", "data", "[", "key", "]", "\n", "return", "ok", "\n", "}" ]
// hasPath returns true if the map contains the given key, false otherwise.
[ "hasPath", "returns", "true", "if", "the", "map", "contains", "the", "given", "key", "false", "otherwise", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L320-L323
149,790
dghubble/go-twitter
twitter/statuses.go
CreatedAtTime
func (t Tweet) CreatedAtTime() (time.Time, error) { return time.Parse(time.RubyDate, t.CreatedAt) }
go
func (t Tweet) CreatedAtTime() (time.Time, error) { return time.Parse(time.RubyDate, t.CreatedAt) }
[ "func", "(", "t", "Tweet", ")", "CreatedAtTime", "(", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "return", "time", ".", "Parse", "(", "time", ".", "RubyDate", ",", "t", ".", "CreatedAt", ")", "\n", "}" ]
// CreatedAtTime returns the time a tweet was created.
[ "CreatedAtTime", "returns", "the", "time", "a", "tweet", "was", "created", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/statuses.go#L54-L56
149,791
dghubble/go-twitter
twitter/direct_messages.go
newDirectMessageService
func newDirectMessageService(sling *sling.Sling) *DirectMessageService { return &DirectMessageService{ baseSling: sling.New(), sling: sling.Path("direct_messages/"), } }
go
func newDirectMessageService(sling *sling.Sling) *DirectMessageService { return &DirectMessageService{ baseSling: sling.New(), sling: sling.Path("direct_messages/"), } }
[ "func", "newDirectMessageService", "(", "sling", "*", "sling", ".", "Sling", ")", "*", "DirectMessageService", "{", "return", "&", "DirectMessageService", "{", "baseSling", ":", "sling", ".", "New", "(", ")", ",", "sling", ":", "sling", ".", "Path", "(", "\"", "\"", ")", ",", "}", "\n", "}" ]
// newDirectMessageService returns a new DirectMessageService.
[ "newDirectMessageService", "returns", "a", "new", "DirectMessageService", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/direct_messages.go#L83-L88
149,792
dghubble/go-twitter
twitter/stream_utils.go
newStreamResponseBodyReader
func newStreamResponseBodyReader(body io.Reader) *streamResponseBodyReader { return &streamResponseBodyReader{reader: bufio.NewReader(body)} }
go
func newStreamResponseBodyReader(body io.Reader) *streamResponseBodyReader { return &streamResponseBodyReader{reader: bufio.NewReader(body)} }
[ "func", "newStreamResponseBodyReader", "(", "body", "io", ".", "Reader", ")", "*", "streamResponseBodyReader", "{", "return", "&", "streamResponseBodyReader", "{", "reader", ":", "bufio", ".", "NewReader", "(", "body", ")", "}", "\n", "}" ]
// newStreamResponseBodyReader returns an instance of streamResponseBodyReader // for the given Twitter stream response body.
[ "newStreamResponseBodyReader", "returns", "an", "instance", "of", "streamResponseBodyReader", "for", "the", "given", "Twitter", "stream", "response", "body", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/stream_utils.go#L43-L45
149,793
dghubble/go-twitter
twitter/stream_utils.go
readNext
func (r *streamResponseBodyReader) readNext() ([]byte, error) { // Discard all the bytes from buf and continue to use the allocated memory // space for reading the next message. r.buf.Truncate(0) for { // Twitter stream messages are separated with "\r\n", and a valid // message may sometimes contain '\n' in the middle. // bufio.Reader.Read() can accept one byte delimiter only, so we need to // first break out each line on '\n' and then check whether the line ends // with "\r\n" to find message boundaries. // https://dev.twitter.com/streaming/overview/processing line, err := r.reader.ReadBytes('\n') // Non-EOF error should be propagated to callers immediately. if err != nil && err != io.EOF { return nil, err } // EOF error means that we reached the end of the stream body before finding // delimiter '\n'. If "line" is empty, it means the reader didn't read any // data from the stream before reaching EOF and there's nothing to append to // buf. if err == io.EOF && len(line) == 0 { // if buf has no data, propagate io.EOF to callers and let them know that // we've finished processing the stream. if r.buf.Len() == 0 { return nil, err } // Otherwise, we still have a remaining stream message to return. break } // If the line ends with "\r\n", it's the end of one stream message data. if bytes.HasSuffix(line, []byte("\r\n")) { // reader.ReadBytes() returns a slice including the delimiter itself, so // we need to trim '\n' as well as '\r' from the end of the slice. r.buf.Write(bytes.TrimRight(line, "\r\n")) break } // Otherwise, the line is not the end of a stream message, so we append // the line to buf and continue to scan lines. r.buf.Write(line) } // Get the stream message bytes from buf. Not that Bytes() won't mark the // returned data as "read", and we need to explicitly call Truncate(0) to // discard from buf before writing the next stream message to buf. return r.buf.Bytes(), nil }
go
func (r *streamResponseBodyReader) readNext() ([]byte, error) { // Discard all the bytes from buf and continue to use the allocated memory // space for reading the next message. r.buf.Truncate(0) for { // Twitter stream messages are separated with "\r\n", and a valid // message may sometimes contain '\n' in the middle. // bufio.Reader.Read() can accept one byte delimiter only, so we need to // first break out each line on '\n' and then check whether the line ends // with "\r\n" to find message boundaries. // https://dev.twitter.com/streaming/overview/processing line, err := r.reader.ReadBytes('\n') // Non-EOF error should be propagated to callers immediately. if err != nil && err != io.EOF { return nil, err } // EOF error means that we reached the end of the stream body before finding // delimiter '\n'. If "line" is empty, it means the reader didn't read any // data from the stream before reaching EOF and there's nothing to append to // buf. if err == io.EOF && len(line) == 0 { // if buf has no data, propagate io.EOF to callers and let them know that // we've finished processing the stream. if r.buf.Len() == 0 { return nil, err } // Otherwise, we still have a remaining stream message to return. break } // If the line ends with "\r\n", it's the end of one stream message data. if bytes.HasSuffix(line, []byte("\r\n")) { // reader.ReadBytes() returns a slice including the delimiter itself, so // we need to trim '\n' as well as '\r' from the end of the slice. r.buf.Write(bytes.TrimRight(line, "\r\n")) break } // Otherwise, the line is not the end of a stream message, so we append // the line to buf and continue to scan lines. r.buf.Write(line) } // Get the stream message bytes from buf. Not that Bytes() won't mark the // returned data as "read", and we need to explicitly call Truncate(0) to // discard from buf before writing the next stream message to buf. return r.buf.Bytes(), nil }
[ "func", "(", "r", "*", "streamResponseBodyReader", ")", "readNext", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Discard all the bytes from buf and continue to use the allocated memory", "// space for reading the next message.", "r", ".", "buf", ".", "Truncate", "(", "0", ")", "\n", "for", "{", "// Twitter stream messages are separated with \"\\r\\n\", and a valid", "// message may sometimes contain '\\n' in the middle.", "// bufio.Reader.Read() can accept one byte delimiter only, so we need to", "// first break out each line on '\\n' and then check whether the line ends", "// with \"\\r\\n\" to find message boundaries.", "// https://dev.twitter.com/streaming/overview/processing", "line", ",", "err", ":=", "r", ".", "reader", ".", "ReadBytes", "(", "'\\n'", ")", "\n", "// Non-EOF error should be propagated to callers immediately.", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// EOF error means that we reached the end of the stream body before finding", "// delimiter '\\n'. If \"line\" is empty, it means the reader didn't read any", "// data from the stream before reaching EOF and there's nothing to append to", "// buf.", "if", "err", "==", "io", ".", "EOF", "&&", "len", "(", "line", ")", "==", "0", "{", "// if buf has no data, propagate io.EOF to callers and let them know that", "// we've finished processing the stream.", "if", "r", ".", "buf", ".", "Len", "(", ")", "==", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Otherwise, we still have a remaining stream message to return.", "break", "\n", "}", "\n", "// If the line ends with \"\\r\\n\", it's the end of one stream message data.", "if", "bytes", ".", "HasSuffix", "(", "line", ",", "[", "]", "byte", "(", "\"", "\\r", "\\n", "\"", ")", ")", "{", "// reader.ReadBytes() returns a slice including the delimiter itself, so", "// we need to trim '\\n' as well as '\\r' from the end of the slice.", "r", ".", "buf", ".", "Write", "(", "bytes", ".", "TrimRight", "(", "line", ",", "\"", "\\r", "\\n", "\"", ")", ")", "\n", "break", "\n", "}", "\n", "// Otherwise, the line is not the end of a stream message, so we append", "// the line to buf and continue to scan lines.", "r", ".", "buf", ".", "Write", "(", "line", ")", "\n", "}", "\n\n", "// Get the stream message bytes from buf. Not that Bytes() won't mark the", "// returned data as \"read\", and we need to explicitly call Truncate(0) to", "// discard from buf before writing the next stream message to buf.", "return", "r", ".", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// readNext reads Twitter stream response body and returns the next stream // content if exists. Returns io.EOF error if we reached the end of the stream // and there's no more message to read.
[ "readNext", "reads", "Twitter", "stream", "response", "body", "and", "returns", "the", "next", "stream", "content", "if", "exists", ".", "Returns", "io", ".", "EOF", "error", "if", "we", "reached", "the", "end", "of", "the", "stream", "and", "there", "s", "no", "more", "message", "to", "read", "." ]
0022a70e9bee80163be82fdd74ac1d92bdebaf57
https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/stream_utils.go#L50-L95
149,794
logrusorgru/aurora
wrap.go
Reset
func Reset(arg interface{}) Value { if val, ok := arg.(Value); ok { return val.Reset() } return value{value: arg} }
go
func Reset(arg interface{}) Value { if val, ok := arg.(Value); ok { return val.Reset() } return value{value: arg} }
[ "func", "Reset", "(", "arg", "interface", "{", "}", ")", "Value", "{", "if", "val", ",", "ok", ":=", "arg", ".", "(", "Value", ")", ";", "ok", "{", "return", "val", ".", "Reset", "(", ")", "\n", "}", "\n", "return", "value", "{", "value", ":", "arg", "}", "\n", "}" ]
// Reset wraps given argument returning Value // without formats and colors.
[ "Reset", "wraps", "given", "argument", "returning", "Value", "without", "formats", "and", "colors", "." ]
cea283e61946ad8227cc02a24201407a2c9e5182
https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/wrap.go#L51-L56
149,795
logrusorgru/aurora
color.go
Nos
func (c Color) Nos(zero bool) string { return string(c.appendNos(make([]byte, 0, 59), zero)) }
go
func (c Color) Nos(zero bool) string { return string(c.appendNos(make([]byte, 0, 59), zero)) }
[ "func", "(", "c", "Color", ")", "Nos", "(", "zero", "bool", ")", "string", "{", "return", "string", "(", "c", ".", "appendNos", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "59", ")", ",", "zero", ")", ")", "\n", "}" ]
// Nos returns string like 1;7;31;45. It // may be an empty string for empty color. // If the zero is true, then the string // is prepended with 0;
[ "Nos", "returns", "string", "like", "1", ";", "7", ";", "31", ";", "45", ".", "It", "may", "be", "an", "empty", "string", "for", "empty", "color", ".", "If", "the", "zero", "is", "true", "then", "the", "string", "is", "prepended", "with", "0", ";" ]
cea283e61946ad8227cc02a24201407a2c9e5182
https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/color.go#L186-L188
149,796
logrusorgru/aurora
color.go
appendSemi
func appendSemi(bs []byte, semi bool, vals ...byte) []byte { if semi { bs = append(bs, ';') } return append(bs, vals...) }
go
func appendSemi(bs []byte, semi bool, vals ...byte) []byte { if semi { bs = append(bs, ';') } return append(bs, vals...) }
[ "func", "appendSemi", "(", "bs", "[", "]", "byte", ",", "semi", "bool", ",", "vals", "...", "byte", ")", "[", "]", "byte", "{", "if", "semi", "{", "bs", "=", "append", "(", "bs", ",", "';'", ")", "\n", "}", "\n", "return", "append", "(", "bs", ",", "vals", "...", ")", "\n", "}" ]
// if the semi is true, then prepend with semicolon
[ "if", "the", "semi", "is", "true", "then", "prepend", "with", "semicolon" ]
cea283e61946ad8227cc02a24201407a2c9e5182
https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/color.go#L198-L203
149,797
logrusorgru/aurora
color.go
appendNos
func (c Color) appendNos(bs []byte, zero bool) []byte { if zero { bs = append(bs, '0') // reset previous } // formats // if c&maskFm != 0 { // 1-2 // don't combine bold and faint using only on of them, preferring bold if c&BoldFm != 0 { bs = appendSemi(bs, zero, '1') } else if c&FaintFm != 0 { bs = appendSemi(bs, zero, '2') } // 3-9 const mask9 = ItalicFm | UnderlineFm | SlowBlinkFm | RapidBlinkFm | ReverseFm | ConcealFm | CrossedOutFm if c&mask9 != 0 { bs = c.appendFm9(bs, zero) } // 20-21 const ( mask21 = FrakturFm | DoublyUnderlineFm mask9i = BoldFm | FaintFm | mask9 ) if c&mask21 != 0 { bs = appendCond(bs, c&FrakturFm != 0, zero || c&mask9i != 0, '2', '0') bs = appendCond(bs, c&DoublyUnderlineFm != 0, zero || c&(mask9i|FrakturFm) != 0, '2', '1') } // 50-53 const ( mask53 = FramedFm | EncircledFm | OverlinedFm mask21i = mask9i | mask21 ) if c&mask53 != 0 { bs = appendCond(bs, c&FramedFm != 0, zero || c&mask21i != 0, '5', '1') bs = appendCond(bs, c&EncircledFm != 0, zero || c&(mask21i|FramedFm) != 0, '5', '2') bs = appendCond(bs, c&OverlinedFm != 0, zero || c&(mask21i|FramedFm|EncircledFm) != 0, '5', '3') } } // foreground if c&maskFg != 0 { bs = c.appendFg(bs, zero) } // background if c&maskBg != 0 { bs = c.appendBg(bs, zero) } return bs }
go
func (c Color) appendNos(bs []byte, zero bool) []byte { if zero { bs = append(bs, '0') // reset previous } // formats // if c&maskFm != 0 { // 1-2 // don't combine bold and faint using only on of them, preferring bold if c&BoldFm != 0 { bs = appendSemi(bs, zero, '1') } else if c&FaintFm != 0 { bs = appendSemi(bs, zero, '2') } // 3-9 const mask9 = ItalicFm | UnderlineFm | SlowBlinkFm | RapidBlinkFm | ReverseFm | ConcealFm | CrossedOutFm if c&mask9 != 0 { bs = c.appendFm9(bs, zero) } // 20-21 const ( mask21 = FrakturFm | DoublyUnderlineFm mask9i = BoldFm | FaintFm | mask9 ) if c&mask21 != 0 { bs = appendCond(bs, c&FrakturFm != 0, zero || c&mask9i != 0, '2', '0') bs = appendCond(bs, c&DoublyUnderlineFm != 0, zero || c&(mask9i|FrakturFm) != 0, '2', '1') } // 50-53 const ( mask53 = FramedFm | EncircledFm | OverlinedFm mask21i = mask9i | mask21 ) if c&mask53 != 0 { bs = appendCond(bs, c&FramedFm != 0, zero || c&mask21i != 0, '5', '1') bs = appendCond(bs, c&EncircledFm != 0, zero || c&(mask21i|FramedFm) != 0, '5', '2') bs = appendCond(bs, c&OverlinedFm != 0, zero || c&(mask21i|FramedFm|EncircledFm) != 0, '5', '3') } } // foreground if c&maskFg != 0 { bs = c.appendFg(bs, zero) } // background if c&maskBg != 0 { bs = c.appendBg(bs, zero) } return bs }
[ "func", "(", "c", "Color", ")", "appendNos", "(", "bs", "[", "]", "byte", ",", "zero", "bool", ")", "[", "]", "byte", "{", "if", "zero", "{", "bs", "=", "append", "(", "bs", ",", "'0'", ")", "// reset previous", "\n", "}", "\n\n", "// formats", "//", "if", "c", "&", "maskFm", "!=", "0", "{", "// 1-2", "// don't combine bold and faint using only on of them, preferring bold", "if", "c", "&", "BoldFm", "!=", "0", "{", "bs", "=", "appendSemi", "(", "bs", ",", "zero", ",", "'1'", ")", "\n", "}", "else", "if", "c", "&", "FaintFm", "!=", "0", "{", "bs", "=", "appendSemi", "(", "bs", ",", "zero", ",", "'2'", ")", "\n", "}", "\n\n", "// 3-9", "const", "mask9", "=", "ItalicFm", "|", "UnderlineFm", "|", "SlowBlinkFm", "|", "RapidBlinkFm", "|", "ReverseFm", "|", "ConcealFm", "|", "CrossedOutFm", "\n\n", "if", "c", "&", "mask9", "!=", "0", "{", "bs", "=", "c", ".", "appendFm9", "(", "bs", ",", "zero", ")", "\n", "}", "\n\n", "// 20-21", "const", "(", "mask21", "=", "FrakturFm", "|", "DoublyUnderlineFm", "\n", "mask9i", "=", "BoldFm", "|", "FaintFm", "|", "mask9", "\n", ")", "\n\n", "if", "c", "&", "mask21", "!=", "0", "{", "bs", "=", "appendCond", "(", "bs", ",", "c", "&", "FrakturFm", "!=", "0", ",", "zero", "||", "c", "&", "mask9i", "!=", "0", ",", "'2'", ",", "'0'", ")", "\n", "bs", "=", "appendCond", "(", "bs", ",", "c", "&", "DoublyUnderlineFm", "!=", "0", ",", "zero", "||", "c", "&", "(", "mask9i", "|", "FrakturFm", ")", "!=", "0", ",", "'2'", ",", "'1'", ")", "\n", "}", "\n\n", "// 50-53", "const", "(", "mask53", "=", "FramedFm", "|", "EncircledFm", "|", "OverlinedFm", "\n", "mask21i", "=", "mask9i", "|", "mask21", "\n", ")", "\n\n", "if", "c", "&", "mask53", "!=", "0", "{", "bs", "=", "appendCond", "(", "bs", ",", "c", "&", "FramedFm", "!=", "0", ",", "zero", "||", "c", "&", "mask21i", "!=", "0", ",", "'5'", ",", "'1'", ")", "\n", "bs", "=", "appendCond", "(", "bs", ",", "c", "&", "EncircledFm", "!=", "0", ",", "zero", "||", "c", "&", "(", "mask21i", "|", "FramedFm", ")", "!=", "0", ",", "'5'", ",", "'2'", ")", "\n", "bs", "=", "appendCond", "(", "bs", ",", "c", "&", "OverlinedFm", "!=", "0", ",", "zero", "||", "c", "&", "(", "mask21i", "|", "FramedFm", "|", "EncircledFm", ")", "!=", "0", ",", "'5'", ",", "'3'", ")", "\n", "}", "\n\n", "}", "\n\n", "// foreground", "if", "c", "&", "maskFg", "!=", "0", "{", "bs", "=", "c", ".", "appendFg", "(", "bs", ",", "zero", ")", "\n", "}", "\n\n", "// background", "if", "c", "&", "maskBg", "!=", "0", "{", "bs", "=", "c", ".", "appendBg", "(", "bs", ",", "zero", ")", "\n", "}", "\n\n", "return", "bs", "\n", "}" ]
// append 1;3;38;5;216 like string that represents ANSI // color of the Color; the zero argument requires // appending of '0' before to reset previous format // and colors
[ "append", "1", ";", "3", ";", "38", ";", "5", ";", "216", "like", "string", "that", "represents", "ANSI", "color", "of", "the", "Color", ";", "the", "zero", "argument", "requires", "appending", "of", "0", "before", "to", "reset", "previous", "format", "and", "colors" ]
cea283e61946ad8227cc02a24201407a2c9e5182
https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/color.go#L309-L388
149,798
gosuri/uilive
writer.go
New
func New() *Writer { termWidth, _ = getTermSize() if termWidth != 0 { overFlowHandled = true } return &Writer{ Out: Out, RefreshInterval: RefreshInterval, mtx: &sync.Mutex{}, } }
go
func New() *Writer { termWidth, _ = getTermSize() if termWidth != 0 { overFlowHandled = true } return &Writer{ Out: Out, RefreshInterval: RefreshInterval, mtx: &sync.Mutex{}, } }
[ "func", "New", "(", ")", "*", "Writer", "{", "termWidth", ",", "_", "=", "getTermSize", "(", ")", "\n", "if", "termWidth", "!=", "0", "{", "overFlowHandled", "=", "true", "\n", "}", "\n\n", "return", "&", "Writer", "{", "Out", ":", "Out", ",", "RefreshInterval", ":", "RefreshInterval", ",", "mtx", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "}", "\n", "}" ]
// New returns a new Writer with defaults
[ "New", "returns", "a", "new", "Writer", "with", "defaults" ]
810653011da975cf3ac54bf7aea22d5c9e49e317
https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L59-L71
149,799
gosuri/uilive
writer.go
Flush
func (w *Writer) Flush() error { w.mtx.Lock() defer w.mtx.Unlock() // do nothing if buffer is empty if len(w.buf.Bytes()) == 0 { return nil } w.clearLines() lines := 0 var currentLine bytes.Buffer for _, b := range w.buf.Bytes() { if b == '\n' { lines++ currentLine.Reset() } else { currentLine.Write([]byte{b}) if overFlowHandled && currentLine.Len() > termWidth { lines++ currentLine.Reset() } } } w.lineCount = lines _, err := w.Out.Write(w.buf.Bytes()) w.buf.Reset() return err }
go
func (w *Writer) Flush() error { w.mtx.Lock() defer w.mtx.Unlock() // do nothing if buffer is empty if len(w.buf.Bytes()) == 0 { return nil } w.clearLines() lines := 0 var currentLine bytes.Buffer for _, b := range w.buf.Bytes() { if b == '\n' { lines++ currentLine.Reset() } else { currentLine.Write([]byte{b}) if overFlowHandled && currentLine.Len() > termWidth { lines++ currentLine.Reset() } } } w.lineCount = lines _, err := w.Out.Write(w.buf.Bytes()) w.buf.Reset() return err }
[ "func", "(", "w", "*", "Writer", ")", "Flush", "(", ")", "error", "{", "w", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// do nothing if buffer is empty", "if", "len", "(", "w", ".", "buf", ".", "Bytes", "(", ")", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "w", ".", "clearLines", "(", ")", "\n\n", "lines", ":=", "0", "\n", "var", "currentLine", "bytes", ".", "Buffer", "\n", "for", "_", ",", "b", ":=", "range", "w", ".", "buf", ".", "Bytes", "(", ")", "{", "if", "b", "==", "'\\n'", "{", "lines", "++", "\n", "currentLine", ".", "Reset", "(", ")", "\n", "}", "else", "{", "currentLine", ".", "Write", "(", "[", "]", "byte", "{", "b", "}", ")", "\n", "if", "overFlowHandled", "&&", "currentLine", ".", "Len", "(", ")", ">", "termWidth", "{", "lines", "++", "\n", "currentLine", ".", "Reset", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "w", ".", "lineCount", "=", "lines", "\n", "_", ",", "err", ":=", "w", ".", "Out", ".", "Write", "(", "w", ".", "buf", ".", "Bytes", "(", ")", ")", "\n", "w", ".", "buf", ".", "Reset", "(", ")", "\n", "return", "err", "\n", "}" ]
// Flush writes to the out and resets the buffer. It should be called after the last call to Write to ensure that any data buffered in the Writer is written to output. // Any incomplete escape sequence at the end is considered complete for formatting purposes. // An error is returned if the contents of the buffer cannot be written to the underlying output stream
[ "Flush", "writes", "to", "the", "out", "and", "resets", "the", "buffer", ".", "It", "should", "be", "called", "after", "the", "last", "call", "to", "Write", "to", "ensure", "that", "any", "data", "buffered", "in", "the", "Writer", "is", "written", "to", "output", ".", "Any", "incomplete", "escape", "sequence", "at", "the", "end", "is", "considered", "complete", "for", "formatting", "purposes", ".", "An", "error", "is", "returned", "if", "the", "contents", "of", "the", "buffer", "cannot", "be", "written", "to", "the", "underlying", "output", "stream" ]
810653011da975cf3ac54bf7aea22d5c9e49e317
https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L76-L104