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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
15,200
cybozu-go/well
reqid.go
WithRequestID
func WithRequestID(ctx context.Context, reqid string) context.Context { return context.WithValue(ctx, RequestIDContextKey, reqid) }
go
func WithRequestID(ctx context.Context, reqid string) context.Context { return context.WithValue(ctx, RequestIDContextKey, reqid) }
[ "func", "WithRequestID", "(", "ctx", "context", ".", "Context", ",", "reqid", "string", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "RequestIDContextKey", ",", "reqid", ")", "\n", "}" ]
// WithRequestID returns a new context with a request ID as a value.
[ "WithRequestID", "returns", "a", "new", "context", "with", "a", "request", "ID", "as", "a", "value", "." ]
cdbf0b975515ab2a1673c52308b0dd1683ebf1e0
https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/reqid.go#L20-L22
15,201
cybozu-go/well
reqid.go
BackgroundWithID
func BackgroundWithID(ctx context.Context) context.Context { id := ctx.Value(RequestIDContextKey) ctx = context.Background() if id == nil { return ctx } return WithRequestID(ctx, id.(string)) }
go
func BackgroundWithID(ctx context.Context) context.Context { id := ctx.Value(RequestIDContextKey) ctx = context.Background() if id == nil { return ctx } return WithRequestID(ctx, id.(string)) }
[ "func", "BackgroundWithID", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "id", ":=", "ctx", ".", "Value", "(", "RequestIDContextKey", ")", "\n", "ctx", "=", "context", ".", "Background", "(", ")", "\n", "if", "id", "==", "nil", "{", "return", "ctx", "\n", "}", "\n", "return", "WithRequestID", "(", "ctx", ",", "id", ".", "(", "string", ")", ")", "\n", "}" ]
// BackgroundWithID returns a new background context with an existing // request ID in ctx, if any.
[ "BackgroundWithID", "returns", "a", "new", "background", "context", "with", "an", "existing", "request", "ID", "in", "ctx", "if", "any", "." ]
cdbf0b975515ab2a1673c52308b0dd1683ebf1e0
https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/reqid.go#L26-L33
15,202
cybozu-go/well
systemd.go
IsSystemdService
func IsSystemdService() bool { if runtime.GOOS != "linux" { return false } // https://www.freedesktop.org/software/systemd/man/systemd.exec.html#%24JOURNAL_STREAM if len(os.Getenv("JOURNAL_STREAM")) > 0 { return true } f, err := os.Open("/proc/self/cgroup") if err != nil { return false } defer f.Close() sc := bufio.NewScanner(f) isService := false for sc.Scan() { fields := strings.Split(sc.Text(), ":") if len(fields) < 3 { continue } if fields[1] != "name=systemd" { continue } isService = strings.HasSuffix(fields[2], ".service") break } if err := sc.Err(); err != nil { return false } return isService }
go
func IsSystemdService() bool { if runtime.GOOS != "linux" { return false } // https://www.freedesktop.org/software/systemd/man/systemd.exec.html#%24JOURNAL_STREAM if len(os.Getenv("JOURNAL_STREAM")) > 0 { return true } f, err := os.Open("/proc/self/cgroup") if err != nil { return false } defer f.Close() sc := bufio.NewScanner(f) isService := false for sc.Scan() { fields := strings.Split(sc.Text(), ":") if len(fields) < 3 { continue } if fields[1] != "name=systemd" { continue } isService = strings.HasSuffix(fields[2], ".service") break } if err := sc.Err(); err != nil { return false } return isService }
[ "func", "IsSystemdService", "(", ")", "bool", "{", "if", "runtime", ".", "GOOS", "!=", "\"", "\"", "{", "return", "false", "\n", "}", "\n\n", "// https://www.freedesktop.org/software/systemd/man/systemd.exec.html#%24JOURNAL_STREAM", "if", "len", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ")", ">", "0", "{", "return", "true", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "sc", ":=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", "isService", ":=", "false", "\n", "for", "sc", ".", "Scan", "(", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "sc", ".", "Text", "(", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "fields", ")", "<", "3", "{", "continue", "\n", "}", "\n", "if", "fields", "[", "1", "]", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "isService", "=", "strings", ".", "HasSuffix", "(", "fields", "[", "2", "]", ",", "\"", "\"", ")", "\n", "break", "\n", "}", "\n", "if", "err", ":=", "sc", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "isService", "\n", "}" ]
// IsSystemdService returns true if the program runs as a systemd service.
[ "IsSystemdService", "returns", "true", "if", "the", "program", "runs", "as", "a", "systemd", "service", "." ]
cdbf0b975515ab2a1673c52308b0dd1683ebf1e0
https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/systemd.go#L11-L45
15,203
andygrunwald/go-gerrit
events.go
getURL
func (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) { parsed, err := url.Parse("/plugins/events-log/events/") if err != nil { return "", err } query := parsed.Query() if !options.From.IsZero() { query.Set("t1", options.From.Format("2006-01-02 15:04:05")) } if !options.To.IsZero() { query.Set("t2", options.To.Format("2006-01-02 15:04:05")) } encoded := query.Encode() if len(encoded) > 0 { parsed.RawQuery = encoded } return parsed.String(), nil }
go
func (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) { parsed, err := url.Parse("/plugins/events-log/events/") if err != nil { return "", err } query := parsed.Query() if !options.From.IsZero() { query.Set("t1", options.From.Format("2006-01-02 15:04:05")) } if !options.To.IsZero() { query.Set("t2", options.To.Format("2006-01-02 15:04:05")) } encoded := query.Encode() if len(encoded) > 0 { parsed.RawQuery = encoded } return parsed.String(), nil }
[ "func", "(", "events", "*", "EventsLogService", ")", "getURL", "(", "options", "*", "EventsLogOptions", ")", "(", "string", ",", "error", ")", "{", "parsed", ",", "err", ":=", "url", ".", "Parse", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "query", ":=", "parsed", ".", "Query", "(", ")", "\n\n", "if", "!", "options", ".", "From", ".", "IsZero", "(", ")", "{", "query", ".", "Set", "(", "\"", "\"", ",", "options", ".", "From", ".", "Format", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "!", "options", ".", "To", ".", "IsZero", "(", ")", "{", "query", ".", "Set", "(", "\"", "\"", ",", "options", ".", "To", ".", "Format", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "encoded", ":=", "query", ".", "Encode", "(", ")", "\n", "if", "len", "(", "encoded", ")", ">", "0", "{", "parsed", ".", "RawQuery", "=", "encoded", "\n", "}", "\n\n", "return", "parsed", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// getURL returns the url that should be used in the request. This will vary // depending on the options provided to GetEvents.
[ "getURL", "returns", "the", "url", "that", "should", "be", "used", "in", "the", "request", ".", "This", "will", "vary", "depending", "on", "the", "options", "provided", "to", "GetEvents", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/events.go#L89-L111
15,204
andygrunwald/go-gerrit
groups.go
getGroupInfoResponse
func (s *GroupsService) getGroupInfoResponse(u string) (*GroupInfo, *Response, error) { req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(GroupInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err }
go
func (s *GroupsService) getGroupInfoResponse(u string) (*GroupInfo, *Response, error) { req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(GroupInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err }
[ "func", "(", "s", "*", "GroupsService", ")", "getGroupInfoResponse", "(", "u", "string", ")", "(", "*", "GroupInfo", ",", "*", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "s", ".", "client", ".", "NewRequest", "(", "\"", "\"", ",", "u", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "v", ":=", "new", "(", "GroupInfo", ")", "\n", "resp", ",", "err", ":=", "s", ".", "client", ".", "Do", "(", "req", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "resp", ",", "err", "\n", "}", "\n\n", "return", "v", ",", "resp", ",", "err", "\n", "}" ]
// getGroupInfoResponse retrieved a single GroupInfo Response for a GET request
[ "getGroupInfoResponse", "retrieved", "a", "single", "GroupInfo", "Response", "for", "a", "GET", "request" ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/groups.go#L130-L143
15,205
andygrunwald/go-gerrit
types.go
MarshalJSON
func (t Timestamp) MarshalJSON() ([]byte, error) { if t.Location() != time.UTC { return nil, errors.New("Timestamp.MarshalJSON: time zone must be UTC") } if y := t.Year(); y < 0 || 9999 < y { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#issuecomment-66073163 for more discussion. return nil, errors.New("Timestamp.MarshalJSON: year outside of range [0,9999]") } b := make([]byte, 0, len(timeLayout)+2) b = append(b, '"') b = t.AppendFormat(b, timeLayout) b = append(b, '"') return b, nil }
go
func (t Timestamp) MarshalJSON() ([]byte, error) { if t.Location() != time.UTC { return nil, errors.New("Timestamp.MarshalJSON: time zone must be UTC") } if y := t.Year(); y < 0 || 9999 < y { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#issuecomment-66073163 for more discussion. return nil, errors.New("Timestamp.MarshalJSON: year outside of range [0,9999]") } b := make([]byte, 0, len(timeLayout)+2) b = append(b, '"') b = t.AppendFormat(b, timeLayout) b = append(b, '"') return b, nil }
[ "func", "(", "t", "Timestamp", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "t", ".", "Location", "(", ")", "!=", "time", ".", "UTC", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "y", ":=", "t", ".", "Year", "(", ")", ";", "y", "<", "0", "||", "9999", "<", "y", "{", "// RFC 3339 is clear that years are 4 digits exactly.", "// See golang.org/issue/4556#issuecomment-66073163 for more discussion.", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "timeLayout", ")", "+", "2", ")", "\n", "b", "=", "append", "(", "b", ",", "'\"'", ")", "\n", "b", "=", "t", ".", "AppendFormat", "(", "b", ",", "timeLayout", ")", "\n", "b", "=", "append", "(", "b", ",", "'\"'", ")", "\n", "return", "b", ",", "nil", "\n", "}" ]
// MarshalJSON implements the json.Marshaler interface. // The time is a quoted string in Gerrit's timestamp format. // An error is returned if t.Time time zone is not UTC.
[ "MarshalJSON", "implements", "the", "json", ".", "Marshaler", "interface", ".", "The", "time", "is", "a", "quoted", "string", "in", "Gerrit", "s", "timestamp", "format", ".", "An", "error", "is", "returned", "if", "t", ".", "Time", "time", "zone", "is", "not", "UTC", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/types.go#L23-L37
15,206
andygrunwald/go-gerrit
types.go
UnmarshalJSON
func (t *Timestamp) UnmarshalJSON(b []byte) error { // Ignore null, like in the main JSON package. if string(b) == "null" { return nil } var err error t.Time, err = time.Parse(`"`+timeLayout+`"`, string(b)) return err }
go
func (t *Timestamp) UnmarshalJSON(b []byte) error { // Ignore null, like in the main JSON package. if string(b) == "null" { return nil } var err error t.Time, err = time.Parse(`"`+timeLayout+`"`, string(b)) return err }
[ "func", "(", "t", "*", "Timestamp", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "// Ignore null, like in the main JSON package.", "if", "string", "(", "b", ")", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "t", ".", "Time", ",", "err", "=", "time", ".", "Parse", "(", "`\"`", "+", "timeLayout", "+", "`\"`", ",", "string", "(", "b", ")", ")", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements the json.Unmarshaler interface. // The time is expected to be a quoted string in Gerrit's timestamp format.
[ "UnmarshalJSON", "implements", "the", "json", ".", "Unmarshaler", "interface", ".", "The", "time", "is", "expected", "to", "be", "a", "quoted", "string", "in", "Gerrit", "s", "timestamp", "format", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/types.go#L41-L49
15,207
andygrunwald/go-gerrit
gerrit.go
checkAuth
func checkAuth(client *Client) (bool, error) { _, response, err := client.Accounts.GetAccount("self") switch err { case ErrWWWAuthenticateHeaderMissing: return false, nil case ErrWWWAuthenticateHeaderNotDigest: return false, nil default: // Response could be nil if the connection outright failed // or some other error occurred before we got a response. if response == nil && err != nil { return false, err } if err != nil && response.StatusCode == http.StatusUnauthorized { err = nil } return response.StatusCode == http.StatusOK, err } }
go
func checkAuth(client *Client) (bool, error) { _, response, err := client.Accounts.GetAccount("self") switch err { case ErrWWWAuthenticateHeaderMissing: return false, nil case ErrWWWAuthenticateHeaderNotDigest: return false, nil default: // Response could be nil if the connection outright failed // or some other error occurred before we got a response. if response == nil && err != nil { return false, err } if err != nil && response.StatusCode == http.StatusUnauthorized { err = nil } return response.StatusCode == http.StatusOK, err } }
[ "func", "checkAuth", "(", "client", "*", "Client", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "response", ",", "err", ":=", "client", ".", "Accounts", ".", "GetAccount", "(", "\"", "\"", ")", "\n", "switch", "err", "{", "case", "ErrWWWAuthenticateHeaderMissing", ":", "return", "false", ",", "nil", "\n", "case", "ErrWWWAuthenticateHeaderNotDigest", ":", "return", "false", ",", "nil", "\n", "default", ":", "// Response could be nil if the connection outright failed", "// or some other error occurred before we got a response.", "if", "response", "==", "nil", "&&", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "err", "!=", "nil", "&&", "response", ".", "StatusCode", "==", "http", ".", "StatusUnauthorized", "{", "err", "=", "nil", "\n", "}", "\n", "return", "response", ".", "StatusCode", "==", "http", ".", "StatusOK", ",", "err", "\n", "}", "\n", "}" ]
// checkAuth is used by NewClient to check if the current credentials are // valid. If the response is 401 Unauthorized then the error will be discarded.
[ "checkAuth", "is", "used", "by", "NewClient", "to", "check", "if", "the", "current", "credentials", "are", "valid", ".", "If", "the", "response", "is", "401", "Unauthorized", "then", "the", "error", "will", "be", "discarded", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/gerrit.go#L193-L212
15,208
andygrunwald/go-gerrit
gerrit.go
NewRequest
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { // Build URL for request u, err := c.buildURLForRequest(urlStr) if err != nil { return nil, err } var buf io.ReadWriter if body != nil { buf = new(bytes.Buffer) err = json.NewEncoder(buf).Encode(body) if err != nil { return nil, err } } req, err := http.NewRequest(method, u, buf) if err != nil { return nil, err } // Apply Authentication if err := c.addAuthentication(req); err != nil { return nil, err } // Request compact JSON // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output req.Header.Add("Accept", "application/json") req.Header.Add("Content-Type", "application/json") // TODO: Add gzip encoding // Accept-Encoding request header is set to gzip // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output return req, nil }
go
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { // Build URL for request u, err := c.buildURLForRequest(urlStr) if err != nil { return nil, err } var buf io.ReadWriter if body != nil { buf = new(bytes.Buffer) err = json.NewEncoder(buf).Encode(body) if err != nil { return nil, err } } req, err := http.NewRequest(method, u, buf) if err != nil { return nil, err } // Apply Authentication if err := c.addAuthentication(req); err != nil { return nil, err } // Request compact JSON // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output req.Header.Add("Accept", "application/json") req.Header.Add("Content-Type", "application/json") // TODO: Add gzip encoding // Accept-Encoding request header is set to gzip // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output return req, nil }
[ "func", "(", "c", "*", "Client", ")", "NewRequest", "(", "method", ",", "urlStr", "string", ",", "body", "interface", "{", "}", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "// Build URL for request", "u", ",", "err", ":=", "c", ".", "buildURLForRequest", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "buf", "io", ".", "ReadWriter", "\n", "if", "body", "!=", "nil", "{", "buf", "=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "err", "=", "json", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "u", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Apply Authentication", "if", "err", ":=", "c", ".", "addAuthentication", "(", "req", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Request compact JSON", "// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// TODO: Add gzip encoding", "// Accept-Encoding request header is set to gzip", "// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output", "return", "req", ",", "nil", "\n", "}" ]
// NewRequest creates an API request. // A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. // Relative URLs should always be specified without a preceding slash. // If specified, the value pointed to by body is JSON encoded and included as the request body.
[ "NewRequest", "creates", "an", "API", "request", ".", "A", "relative", "URL", "can", "be", "provided", "in", "urlStr", "in", "which", "case", "it", "is", "resolved", "relative", "to", "the", "baseURL", "of", "the", "Client", ".", "Relative", "URLs", "should", "always", "be", "specified", "without", "a", "preceding", "slash", ".", "If", "specified", "the", "value", "pointed", "to", "by", "body", "is", "JSON", "encoded", "and", "included", "as", "the", "request", "body", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/gerrit.go#L218-L254
15,209
andygrunwald/go-gerrit
gerrit.go
NewRawPutRequest
func (c *Client) NewRawPutRequest(urlStr string, body string) (*http.Request, error) { // Build URL for request u, err := c.buildURLForRequest(urlStr) if err != nil { return nil, err } buf := bytes.NewBuffer([]byte(body)) req, err := http.NewRequest("PUT", u, buf) if err != nil { return nil, err } // Apply Authentication if err := c.addAuthentication(req); err != nil { return nil, err } // Request compact JSON // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output req.Header.Add("Accept", "application/json") req.Header.Add("Content-Type", "application/x-www-form-urlencoded") // TODO: Add gzip encoding // Accept-Encoding request header is set to gzip // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output return req, nil }
go
func (c *Client) NewRawPutRequest(urlStr string, body string) (*http.Request, error) { // Build URL for request u, err := c.buildURLForRequest(urlStr) if err != nil { return nil, err } buf := bytes.NewBuffer([]byte(body)) req, err := http.NewRequest("PUT", u, buf) if err != nil { return nil, err } // Apply Authentication if err := c.addAuthentication(req); err != nil { return nil, err } // Request compact JSON // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output req.Header.Add("Accept", "application/json") req.Header.Add("Content-Type", "application/x-www-form-urlencoded") // TODO: Add gzip encoding // Accept-Encoding request header is set to gzip // See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output return req, nil }
[ "func", "(", "c", "*", "Client", ")", "NewRawPutRequest", "(", "urlStr", "string", ",", "body", "string", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "// Build URL for request", "u", ",", "err", ":=", "c", ".", "buildURLForRequest", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "body", ")", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "u", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Apply Authentication", "if", "err", ":=", "c", ".", "addAuthentication", "(", "req", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Request compact JSON", "// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// TODO: Add gzip encoding", "// Accept-Encoding request header is set to gzip", "// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output", "return", "req", ",", "nil", "\n", "}" ]
// NewRawPutRequest creates a raw PUT request and makes no attempt to encode // or marshal the body. Just passes it straight through.
[ "NewRawPutRequest", "creates", "a", "raw", "PUT", "request", "and", "makes", "no", "attempt", "to", "encode", "or", "marshal", "the", "body", ".", "Just", "passes", "it", "straight", "through", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/gerrit.go#L258-L286
15,210
andygrunwald/go-gerrit
gerrit.go
DeleteRequest
func (c *Client) DeleteRequest(urlStr string, body interface{}) (*Response, error) { req, err := c.NewRequest("DELETE", urlStr, body) if err != nil { return nil, err } return c.Do(req, nil) }
go
func (c *Client) DeleteRequest(urlStr string, body interface{}) (*Response, error) { req, err := c.NewRequest("DELETE", urlStr, body) if err != nil { return nil, err } return c.Do(req, nil) }
[ "func", "(", "c", "*", "Client", ")", "DeleteRequest", "(", "urlStr", "string", ",", "body", "interface", "{", "}", ")", "(", "*", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "urlStr", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "c", ".", "Do", "(", "req", ",", "nil", ")", "\n", "}" ]
// DeleteRequest sends an DELETE API Request to urlStr with optional body. // It is a shorthand combination for Client.NewRequest with Client.Do. // // Relative URLs should always be specified without a preceding slash. // If specified, the value pointed to by body is JSON encoded and included as the request body.
[ "DeleteRequest", "sends", "an", "DELETE", "API", "Request", "to", "urlStr", "with", "optional", "body", ".", "It", "is", "a", "shorthand", "combination", "for", "Client", ".", "NewRequest", "with", "Client", ".", "Do", ".", "Relative", "URLs", "should", "always", "be", "specified", "without", "a", "preceding", "slash", ".", "If", "specified", "the", "value", "pointed", "to", "by", "body", "is", "JSON", "encoded", "and", "included", "as", "the", "request", "body", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/gerrit.go#L449-L456
15,211
andygrunwald/go-gerrit
gerrit.go
getStringResponseWithoutOptions
func getStringResponseWithoutOptions(client *Client, u string) (string, *Response, error) { v := new(string) resp, err := client.Call("GET", u, nil, v) return *v, resp, err }
go
func getStringResponseWithoutOptions(client *Client, u string) (string, *Response, error) { v := new(string) resp, err := client.Call("GET", u, nil, v) return *v, resp, err }
[ "func", "getStringResponseWithoutOptions", "(", "client", "*", "Client", ",", "u", "string", ")", "(", "string", ",", "*", "Response", ",", "error", ")", "{", "v", ":=", "new", "(", "string", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Call", "(", "\"", "\"", ",", "u", ",", "nil", ",", "v", ")", "\n", "return", "*", "v", ",", "resp", ",", "err", "\n", "}" ]
// getStringResponseWithoutOptions retrieved a single string Response for a GET request
[ "getStringResponseWithoutOptions", "retrieved", "a", "single", "string", "Response", "for", "a", "GET", "request" ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/gerrit.go#L560-L564
15,212
andygrunwald/go-gerrit
authentication.go
SetBasicAuth
func (s *AuthenticationService) SetBasicAuth(username, password string) { s.name = username s.secret = password s.authType = authTypeBasic }
go
func (s *AuthenticationService) SetBasicAuth(username, password string) { s.name = username s.secret = password s.authType = authTypeBasic }
[ "func", "(", "s", "*", "AuthenticationService", ")", "SetBasicAuth", "(", "username", ",", "password", "string", ")", "{", "s", ".", "name", "=", "username", "\n", "s", ".", "secret", "=", "password", "\n", "s", ".", "authType", "=", "authTypeBasic", "\n", "}" ]
// SetBasicAuth sets basic parameters for HTTP Basic auth
[ "SetBasicAuth", "sets", "basic", "parameters", "for", "HTTP", "Basic", "auth" ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/authentication.go#L49-L53
15,213
andygrunwald/go-gerrit
authentication.go
SetDigestAuth
func (s *AuthenticationService) SetDigestAuth(username, password string) { s.name = username s.secret = password s.authType = authTypeDigest }
go
func (s *AuthenticationService) SetDigestAuth(username, password string) { s.name = username s.secret = password s.authType = authTypeDigest }
[ "func", "(", "s", "*", "AuthenticationService", ")", "SetDigestAuth", "(", "username", ",", "password", "string", ")", "{", "s", ".", "name", "=", "username", "\n", "s", ".", "secret", "=", "password", "\n", "s", ".", "authType", "=", "authTypeDigest", "\n", "}" ]
// SetDigestAuth sets digest parameters for HTTP Digest auth.
[ "SetDigestAuth", "sets", "digest", "parameters", "for", "HTTP", "Digest", "auth", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/authentication.go#L56-L60
15,214
andygrunwald/go-gerrit
authentication.go
SetCookieAuth
func (s *AuthenticationService) SetCookieAuth(name, value string) { s.name = name s.secret = value s.authType = authTypeCookie }
go
func (s *AuthenticationService) SetCookieAuth(name, value string) { s.name = name s.secret = value s.authType = authTypeCookie }
[ "func", "(", "s", "*", "AuthenticationService", ")", "SetCookieAuth", "(", "name", ",", "value", "string", ")", "{", "s", ".", "name", "=", "name", "\n", "s", ".", "secret", "=", "value", "\n", "s", ".", "authType", "=", "authTypeCookie", "\n", "}" ]
// SetCookieAuth sets basic parameters for HTTP Cookie
[ "SetCookieAuth", "sets", "basic", "parameters", "for", "HTTP", "Cookie" ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/authentication.go#L156-L160
15,215
andygrunwald/go-gerrit
changes.go
getChangeInfoResponse
func (s *ChangesService) getChangeInfoResponse(u string, opt *ChangeOptions) (*ChangeInfo, *Response, error) { u, err := addOptions(u, opt) if err != nil { return nil, nil, err } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(ChangeInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err }
go
func (s *ChangesService) getChangeInfoResponse(u string, opt *ChangeOptions) (*ChangeInfo, *Response, error) { u, err := addOptions(u, opt) if err != nil { return nil, nil, err } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(ChangeInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err }
[ "func", "(", "s", "*", "ChangesService", ")", "getChangeInfoResponse", "(", "u", "string", ",", "opt", "*", "ChangeOptions", ")", "(", "*", "ChangeInfo", ",", "*", "Response", ",", "error", ")", "{", "u", ",", "err", ":=", "addOptions", "(", "u", ",", "opt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "req", ",", "err", ":=", "s", ".", "client", ".", "NewRequest", "(", "\"", "\"", ",", "u", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "v", ":=", "new", "(", "ChangeInfo", ")", "\n", "resp", ",", "err", ":=", "s", ".", "client", ".", "Do", "(", "req", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "resp", ",", "err", "\n", "}", "\n\n", "return", "v", ",", "resp", ",", "err", "\n", "}" ]
// getChangeInfoResponse retrieved a single ChangeInfo Response for a GET request
[ "getChangeInfoResponse", "retrieved", "a", "single", "ChangeInfo", "Response", "for", "a", "GET", "request" ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/changes.go#L506-L524
15,216
andygrunwald/go-gerrit
changes.go
getCommentInfoMapResponse
func (s *ChangesService) getCommentInfoMapResponse(u string) (*map[string][]CommentInfo, *Response, error) { req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(map[string][]CommentInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err }
go
func (s *ChangesService) getCommentInfoMapResponse(u string) (*map[string][]CommentInfo, *Response, error) { req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(map[string][]CommentInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err }
[ "func", "(", "s", "*", "ChangesService", ")", "getCommentInfoMapResponse", "(", "u", "string", ")", "(", "*", "map", "[", "string", "]", "[", "]", "CommentInfo", ",", "*", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "s", ".", "client", ".", "NewRequest", "(", "\"", "\"", ",", "u", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "v", ":=", "new", "(", "map", "[", "string", "]", "[", "]", "CommentInfo", ")", "\n", "resp", ",", "err", ":=", "s", ".", "client", ".", "Do", "(", "req", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "resp", ",", "err", "\n", "}", "\n\n", "return", "v", ",", "resp", ",", "err", "\n", "}" ]
// getCommentInfoMapResponse retrieved a map of CommentInfo Response for a GET request
[ "getCommentInfoMapResponse", "retrieved", "a", "map", "of", "CommentInfo", "Response", "for", "a", "GET", "request" ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/changes.go#L596-L609
15,217
andygrunwald/go-gerrit
changes.go
change
func (s *ChangesService) change(tail string, changeID string, input interface{}) (*ChangeInfo, *Response, error) { u := fmt.Sprintf("changes/%s/%s", changeID, tail) req, err := s.client.NewRequest("POST", u, input) if err != nil { return nil, nil, err } v := new(ChangeInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } if resp.StatusCode == http.StatusConflict { body, err := ioutil.ReadAll(resp.Body) if err != nil { return v, resp, err } return v, resp, errors.New(string(body[:])) } return v, resp, nil }
go
func (s *ChangesService) change(tail string, changeID string, input interface{}) (*ChangeInfo, *Response, error) { u := fmt.Sprintf("changes/%s/%s", changeID, tail) req, err := s.client.NewRequest("POST", u, input) if err != nil { return nil, nil, err } v := new(ChangeInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } if resp.StatusCode == http.StatusConflict { body, err := ioutil.ReadAll(resp.Body) if err != nil { return v, resp, err } return v, resp, errors.New(string(body[:])) } return v, resp, nil }
[ "func", "(", "s", "*", "ChangesService", ")", "change", "(", "tail", "string", ",", "changeID", "string", ",", "input", "interface", "{", "}", ")", "(", "*", "ChangeInfo", ",", "*", "Response", ",", "error", ")", "{", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "changeID", ",", "tail", ")", "\n", "req", ",", "err", ":=", "s", ".", "client", ".", "NewRequest", "(", "\"", "\"", ",", "u", ",", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "v", ":=", "new", "(", "ChangeInfo", ")", "\n", "resp", ",", "err", ":=", "s", ".", "client", ".", "Do", "(", "req", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "resp", ",", "err", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "==", "http", ".", "StatusConflict", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "resp", ",", "err", "\n", "}", "\n", "return", "v", ",", "resp", ",", "errors", ".", "New", "(", "string", "(", "body", "[", ":", "]", ")", ")", "\n", "}", "\n", "return", "v", ",", "resp", ",", "nil", "\n", "}" ]
// change is an internal function to consolidate code used by SubmitChange, // AbandonChange and other similar functions.
[ "change", "is", "an", "internal", "function", "to", "consolidate", "code", "used", "by", "SubmitChange", "AbandonChange", "and", "other", "similar", "functions", "." ]
174420ebee6cb397f25bd5623b250cff9e5aec9a
https://github.com/andygrunwald/go-gerrit/blob/174420ebee6cb397f25bd5623b250cff9e5aec9a/changes.go#L774-L794
15,218
gobuffalo/suite
suite.go
NewAction
func NewAction(app *buffalo.App) *Action { as := &Action{ App: app, Model: NewModel(), } return as }
go
func NewAction(app *buffalo.App) *Action { as := &Action{ App: app, Model: NewModel(), } return as }
[ "func", "NewAction", "(", "app", "*", "buffalo", ".", "App", ")", "*", "Action", "{", "as", ":=", "&", "Action", "{", "App", ":", "app", ",", "Model", ":", "NewModel", "(", ")", ",", "}", "\n", "return", "as", "\n", "}" ]
// NewAction returns new Action for given buffalo.App
[ "NewAction", "returns", "new", "Action", "for", "given", "buffalo", ".", "App" ]
917e29a4226b0b4d66176c8db37947b73eb22623
https://github.com/gobuffalo/suite/blob/917e29a4226b0b4d66176c8db37947b73eb22623/suite.go#L22-L28
15,219
evalphobia/logrus_fluent
reflect.go
ConvertToValue
func ConvertToValue(p interface{}, tagName string) interface{} { rv := toValue(p) switch rv.Kind() { case reflect.Struct: return convertFromStruct(rv.Interface(), tagName) case reflect.Map: return convertFromMap(rv, tagName) case reflect.Slice: return convertFromSlice(rv, tagName) case reflect.Chan: return nil case reflect.Invalid: return nil default: return rv.Interface() } }
go
func ConvertToValue(p interface{}, tagName string) interface{} { rv := toValue(p) switch rv.Kind() { case reflect.Struct: return convertFromStruct(rv.Interface(), tagName) case reflect.Map: return convertFromMap(rv, tagName) case reflect.Slice: return convertFromSlice(rv, tagName) case reflect.Chan: return nil case reflect.Invalid: return nil default: return rv.Interface() } }
[ "func", "ConvertToValue", "(", "p", "interface", "{", "}", ",", "tagName", "string", ")", "interface", "{", "}", "{", "rv", ":=", "toValue", "(", "p", ")", "\n", "switch", "rv", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "return", "convertFromStruct", "(", "rv", ".", "Interface", "(", ")", ",", "tagName", ")", "\n", "case", "reflect", ".", "Map", ":", "return", "convertFromMap", "(", "rv", ",", "tagName", ")", "\n", "case", "reflect", ".", "Slice", ":", "return", "convertFromSlice", "(", "rv", ",", "tagName", ")", "\n", "case", "reflect", ".", "Chan", ":", "return", "nil", "\n", "case", "reflect", ".", "Invalid", ":", "return", "nil", "\n", "default", ":", "return", "rv", ".", "Interface", "(", ")", "\n", "}", "\n", "}" ]
// ConvertToValue make map data from struct and tags
[ "ConvertToValue", "make", "map", "data", "from", "struct", "and", "tags" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L10-L26
15,220
evalphobia/logrus_fluent
reflect.go
toValue
func toValue(p interface{}) reflect.Value { v := reflect.ValueOf(p) if v.Kind() == reflect.Ptr { v = v.Elem() } return v }
go
func toValue(p interface{}) reflect.Value { v := reflect.ValueOf(p) if v.Kind() == reflect.Ptr { v = v.Elem() } return v }
[ "func", "toValue", "(", "p", "interface", "{", "}", ")", "reflect", ".", "Value", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "p", ")", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n", "return", "v", "\n", "}" ]
// toValue converts any value to reflect.Value
[ "toValue", "converts", "any", "value", "to", "reflect", ".", "Value" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L97-L103
15,221
evalphobia/logrus_fluent
reflect.go
toType
func toType(p interface{}) reflect.Type { t := reflect.ValueOf(p).Type() if t.Kind() == reflect.Ptr { t = t.Elem() } return t }
go
func toType(p interface{}) reflect.Type { t := reflect.ValueOf(p).Type() if t.Kind() == reflect.Ptr { t = t.Elem() } return t }
[ "func", "toType", "(", "p", "interface", "{", "}", ")", "reflect", ".", "Type", "{", "t", ":=", "reflect", ".", "ValueOf", "(", "p", ")", ".", "Type", "(", ")", "\n", "if", "t", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "t", "=", "t", ".", "Elem", "(", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// toType converts any value to reflect.Type
[ "toType", "converts", "any", "value", "to", "reflect", ".", "Type" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L106-L112
15,222
evalphobia/logrus_fluent
reflect.go
isZero
func isZero(v reflect.Value) bool { zero := reflect.Zero(v.Type()).Interface() value := v.Interface() return reflect.DeepEqual(value, zero) }
go
func isZero(v reflect.Value) bool { zero := reflect.Zero(v.Type()).Interface() value := v.Interface() return reflect.DeepEqual(value, zero) }
[ "func", "isZero", "(", "v", "reflect", ".", "Value", ")", "bool", "{", "zero", ":=", "reflect", ".", "Zero", "(", "v", ".", "Type", "(", ")", ")", ".", "Interface", "(", ")", "\n", "value", ":=", "v", ".", "Interface", "(", ")", "\n", "return", "reflect", ".", "DeepEqual", "(", "value", ",", "zero", ")", "\n", "}" ]
// isZero checks the value is zero-value or not
[ "isZero", "checks", "the", "value", "is", "zero", "-", "value", "or", "not" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L115-L119
15,223
evalphobia/logrus_fluent
reflect.go
getNameFromTag
func getNameFromTag(f reflect.StructField, tagName string) string { tag, _ := parseTag(f, tagName) if tag != "" { return tag } return f.Name }
go
func getNameFromTag(f reflect.StructField, tagName string) string { tag, _ := parseTag(f, tagName) if tag != "" { return tag } return f.Name }
[ "func", "getNameFromTag", "(", "f", "reflect", ".", "StructField", ",", "tagName", "string", ")", "string", "{", "tag", ",", "_", ":=", "parseTag", "(", "f", ",", "tagName", ")", "\n", "if", "tag", "!=", "\"", "\"", "{", "return", "tag", "\n", "}", "\n", "return", "f", ".", "Name", "\n", "}" ]
// getNameFromTag return the value in tag or field name in the struct field
[ "getNameFromTag", "return", "the", "value", "in", "tag", "or", "field", "name", "in", "the", "struct", "field" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L122-L128
15,224
evalphobia/logrus_fluent
reflect.go
getTagValues
func getTagValues(f reflect.StructField, tag string) string { return f.Tag.Get(tag) }
go
func getTagValues(f reflect.StructField, tag string) string { return f.Tag.Get(tag) }
[ "func", "getTagValues", "(", "f", "reflect", ".", "StructField", ",", "tag", "string", ")", "string", "{", "return", "f", ".", "Tag", ".", "Get", "(", "tag", ")", "\n", "}" ]
// getTagValues returns tag value of the struct field
[ "getTagValues", "returns", "tag", "value", "of", "the", "struct", "field" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L131-L133
15,225
evalphobia/logrus_fluent
reflect.go
parseTag
func parseTag(f reflect.StructField, tag string) (string, options) { return splitTags(getTagValues(f, tag)) }
go
func parseTag(f reflect.StructField, tag string) (string, options) { return splitTags(getTagValues(f, tag)) }
[ "func", "parseTag", "(", "f", "reflect", ".", "StructField", ",", "tag", "string", ")", "(", "string", ",", "options", ")", "{", "return", "splitTags", "(", "getTagValues", "(", "f", ",", "tag", ")", ")", "\n", "}" ]
// parseTag returns the first tag value of the struct field
[ "parseTag", "returns", "the", "first", "tag", "value", "of", "the", "struct", "field" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L136-L138
15,226
evalphobia/logrus_fluent
reflect.go
splitTags
func splitTags(tags string) (string, options) { res := strings.Split(tags, ",") return res[0], res[1:] }
go
func splitTags(tags string) (string, options) { res := strings.Split(tags, ",") return res[0], res[1:] }
[ "func", "splitTags", "(", "tags", "string", ")", "(", "string", ",", "options", ")", "{", "res", ":=", "strings", ".", "Split", "(", "tags", ",", "\"", "\"", ")", "\n", "return", "res", "[", "0", "]", ",", "res", "[", "1", ":", "]", "\n", "}" ]
// splitTags returns the first tag value and rest slice
[ "splitTags", "returns", "the", "first", "tag", "value", "and", "rest", "slice" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L141-L144
15,227
evalphobia/logrus_fluent
reflect.go
Has
func (t options) Has(tag string) bool { for _, opt := range t { if opt == tag { return true } } return false }
go
func (t options) Has(tag string) bool { for _, opt := range t { if opt == tag { return true } } return false }
[ "func", "(", "t", "options", ")", "Has", "(", "tag", "string", ")", "bool", "{", "for", "_", ",", "opt", ":=", "range", "t", "{", "if", "opt", "==", "tag", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Has checks the value exists in the rest values or not
[ "Has", "checks", "the", "value", "exists", "in", "the", "rest", "values", "or", "not" ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/reflect.go#L150-L157
15,228
evalphobia/logrus_fluent
filter.go
FilterError
func FilterError(v interface{}) interface{} { if err, ok := v.(error); ok { return err.Error() } return v }
go
func FilterError(v interface{}) interface{} { if err, ok := v.(error); ok { return err.Error() } return v }
[ "func", "FilterError", "(", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "err", ",", "ok", ":=", "v", ".", "(", "error", ")", ";", "ok", "{", "return", "err", ".", "Error", "(", ")", "\n", "}", "\n", "return", "v", "\n", "}" ]
// FilterError is a filter function to convert error type to string type.
[ "FilterError", "is", "a", "filter", "function", "to", "convert", "error", "type", "to", "string", "type", "." ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/filter.go#L4-L9
15,229
evalphobia/logrus_fluent
fluent.go
New
func New(host string, port int) (*FluentHook, error) { return NewWithConfig(Config{ Host: host, Port: port, DefaultMessageField: MessageField, }) }
go
func New(host string, port int) (*FluentHook, error) { return NewWithConfig(Config{ Host: host, Port: port, DefaultMessageField: MessageField, }) }
[ "func", "New", "(", "host", "string", ",", "port", "int", ")", "(", "*", "FluentHook", ",", "error", ")", "{", "return", "NewWithConfig", "(", "Config", "{", "Host", ":", "host", ",", "Port", ":", "port", ",", "DefaultMessageField", ":", "MessageField", ",", "}", ")", "\n", "}" ]
// New returns initialized logrus hook for fluentd with persistent fluentd logger.
[ "New", "returns", "initialized", "logrus", "hook", "for", "fluentd", "with", "persistent", "fluentd", "logger", "." ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/fluent.go#L50-L56
15,230
evalphobia/logrus_fluent
fluent.go
NewWithConfig
func NewWithConfig(conf Config) (*FluentHook, error) { var fd *fluent.Fluent if !conf.DisableConnectionPool { var err error fd, err = fluent.New(conf.FluentConfig()) if err != nil { return nil, err } } hook := &FluentHook{ Fluent: fd, conf: conf, levels: conf.LogLevels, ignoreFields: make(map[string]struct{}), filters: make(map[string]func(interface{}) interface{}), } // set default values if len(hook.levels) == 0 { hook.levels = defaultLevels } if conf.DefaultTag != "" { tag := conf.DefaultTag hook.tag = &tag } if conf.DefaultMessageField != "" { hook.messageField = conf.DefaultMessageField } for k, v := range conf.DefaultIgnoreFields { hook.ignoreFields[k] = v } for k, v := range conf.DefaultFilters { hook.filters[k] = v } return hook, nil }
go
func NewWithConfig(conf Config) (*FluentHook, error) { var fd *fluent.Fluent if !conf.DisableConnectionPool { var err error fd, err = fluent.New(conf.FluentConfig()) if err != nil { return nil, err } } hook := &FluentHook{ Fluent: fd, conf: conf, levels: conf.LogLevels, ignoreFields: make(map[string]struct{}), filters: make(map[string]func(interface{}) interface{}), } // set default values if len(hook.levels) == 0 { hook.levels = defaultLevels } if conf.DefaultTag != "" { tag := conf.DefaultTag hook.tag = &tag } if conf.DefaultMessageField != "" { hook.messageField = conf.DefaultMessageField } for k, v := range conf.DefaultIgnoreFields { hook.ignoreFields[k] = v } for k, v := range conf.DefaultFilters { hook.filters[k] = v } return hook, nil }
[ "func", "NewWithConfig", "(", "conf", "Config", ")", "(", "*", "FluentHook", ",", "error", ")", "{", "var", "fd", "*", "fluent", ".", "Fluent", "\n", "if", "!", "conf", ".", "DisableConnectionPool", "{", "var", "err", "error", "\n", "fd", ",", "err", "=", "fluent", ".", "New", "(", "conf", ".", "FluentConfig", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "hook", ":=", "&", "FluentHook", "{", "Fluent", ":", "fd", ",", "conf", ":", "conf", ",", "levels", ":", "conf", ".", "LogLevels", ",", "ignoreFields", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "filters", ":", "make", "(", "map", "[", "string", "]", "func", "(", "interface", "{", "}", ")", "interface", "{", "}", ")", ",", "}", "\n", "// set default values", "if", "len", "(", "hook", ".", "levels", ")", "==", "0", "{", "hook", ".", "levels", "=", "defaultLevels", "\n", "}", "\n", "if", "conf", ".", "DefaultTag", "!=", "\"", "\"", "{", "tag", ":=", "conf", ".", "DefaultTag", "\n", "hook", ".", "tag", "=", "&", "tag", "\n", "}", "\n", "if", "conf", ".", "DefaultMessageField", "!=", "\"", "\"", "{", "hook", ".", "messageField", "=", "conf", ".", "DefaultMessageField", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "conf", ".", "DefaultIgnoreFields", "{", "hook", ".", "ignoreFields", "[", "k", "]", "=", "v", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "conf", ".", "DefaultFilters", "{", "hook", ".", "filters", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "return", "hook", ",", "nil", "\n", "}" ]
// NewWithConfig returns initialized logrus hook by config setting.
[ "NewWithConfig", "returns", "initialized", "logrus", "hook", "by", "config", "setting", "." ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/fluent.go#L59-L95
15,231
evalphobia/logrus_fluent
fluent.go
Fire
func (hook *FluentHook) Fire(entry *logrus.Entry) error { var logger *fluent.Fluent var err error switch { case hook.Fluent != nil: logger = hook.Fluent default: logger, err = fluent.New(hook.conf.FluentConfig()) if err != nil { return err } defer logger.Close() } // Create a map for passing to FluentD data := make(logrus.Fields) for k, v := range entry.Data { if _, ok := hook.ignoreFields[k]; ok { continue } if fn, ok := hook.filters[k]; ok { v = fn(v) } data[k] = v } setLevelString(entry, data) tag := hook.getTagAndDel(entry, data) if tag != entry.Message { hook.setMessage(entry, data) } fluentData := ConvertToValue(data, TagName) err = logger.PostWithTime(tag, entry.Time, fluentData) return err }
go
func (hook *FluentHook) Fire(entry *logrus.Entry) error { var logger *fluent.Fluent var err error switch { case hook.Fluent != nil: logger = hook.Fluent default: logger, err = fluent.New(hook.conf.FluentConfig()) if err != nil { return err } defer logger.Close() } // Create a map for passing to FluentD data := make(logrus.Fields) for k, v := range entry.Data { if _, ok := hook.ignoreFields[k]; ok { continue } if fn, ok := hook.filters[k]; ok { v = fn(v) } data[k] = v } setLevelString(entry, data) tag := hook.getTagAndDel(entry, data) if tag != entry.Message { hook.setMessage(entry, data) } fluentData := ConvertToValue(data, TagName) err = logger.PostWithTime(tag, entry.Time, fluentData) return err }
[ "func", "(", "hook", "*", "FluentHook", ")", "Fire", "(", "entry", "*", "logrus", ".", "Entry", ")", "error", "{", "var", "logger", "*", "fluent", ".", "Fluent", "\n", "var", "err", "error", "\n\n", "switch", "{", "case", "hook", ".", "Fluent", "!=", "nil", ":", "logger", "=", "hook", ".", "Fluent", "\n", "default", ":", "logger", ",", "err", "=", "fluent", ".", "New", "(", "hook", ".", "conf", ".", "FluentConfig", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "logger", ".", "Close", "(", ")", "\n", "}", "\n\n", "// Create a map for passing to FluentD", "data", ":=", "make", "(", "logrus", ".", "Fields", ")", "\n", "for", "k", ",", "v", ":=", "range", "entry", ".", "Data", "{", "if", "_", ",", "ok", ":=", "hook", ".", "ignoreFields", "[", "k", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "hook", ".", "filters", "[", "k", "]", ";", "ok", "{", "v", "=", "fn", "(", "v", ")", "\n", "}", "\n", "data", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "setLevelString", "(", "entry", ",", "data", ")", "\n", "tag", ":=", "hook", ".", "getTagAndDel", "(", "entry", ",", "data", ")", "\n", "if", "tag", "!=", "entry", ".", "Message", "{", "hook", ".", "setMessage", "(", "entry", ",", "data", ")", "\n", "}", "\n\n", "fluentData", ":=", "ConvertToValue", "(", "data", ",", "TagName", ")", "\n", "err", "=", "logger", ".", "PostWithTime", "(", "tag", ",", "entry", ".", "Time", ",", "fluentData", ")", "\n", "return", "err", "\n", "}" ]
// Fire is invoked by logrus and sends log to fluentd logger.
[ "Fire", "is", "invoked", "by", "logrus", "and", "sends", "log", "to", "fluentd", "logger", "." ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/fluent.go#L149-L185
15,232
evalphobia/logrus_fluent
fluent.go
getTagAndDel
func (hook *FluentHook) getTagAndDel(entry *logrus.Entry, data logrus.Fields) string { // use static tag from if hook.tag != nil { return *hook.tag } tagField, ok := data[TagField] if !ok { return entry.Message } tag, ok := tagField.(string) if !ok { return entry.Message } // remove tag from data fields delete(data, TagField) return tag }
go
func (hook *FluentHook) getTagAndDel(entry *logrus.Entry, data logrus.Fields) string { // use static tag from if hook.tag != nil { return *hook.tag } tagField, ok := data[TagField] if !ok { return entry.Message } tag, ok := tagField.(string) if !ok { return entry.Message } // remove tag from data fields delete(data, TagField) return tag }
[ "func", "(", "hook", "*", "FluentHook", ")", "getTagAndDel", "(", "entry", "*", "logrus", ".", "Entry", ",", "data", "logrus", ".", "Fields", ")", "string", "{", "// use static tag from", "if", "hook", ".", "tag", "!=", "nil", "{", "return", "*", "hook", ".", "tag", "\n", "}", "\n\n", "tagField", ",", "ok", ":=", "data", "[", "TagField", "]", "\n", "if", "!", "ok", "{", "return", "entry", ".", "Message", "\n", "}", "\n\n", "tag", ",", "ok", ":=", "tagField", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "entry", ".", "Message", "\n", "}", "\n\n", "// remove tag from data fields", "delete", "(", "data", ",", "TagField", ")", "\n", "return", "tag", "\n", "}" ]
// getTagAndDel extracts tag data from log entry and custom log fields. // 1. if tag is set in the hook, use it. // 2. if tag is set in custom fields, use it. // 3. if cannot find tag data, use entry.Message as tag.
[ "getTagAndDel", "extracts", "tag", "data", "from", "log", "entry", "and", "custom", "log", "fields", ".", "1", ".", "if", "tag", "is", "set", "in", "the", "hook", "use", "it", ".", "2", ".", "if", "tag", "is", "set", "in", "custom", "fields", "use", "it", ".", "3", ".", "if", "cannot", "find", "tag", "data", "use", "entry", ".", "Message", "as", "tag", "." ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/fluent.go#L191-L210
15,233
evalphobia/logrus_fluent
config.go
FluentConfig
func (c Config) FluentConfig() fluent.Config { return fluent.Config{ FluentPort: c.Port, FluentHost: c.Host, FluentNetwork: c.FluentNetwork, FluentSocketPath: c.FluentSocketPath, Timeout: c.Timeout, WriteTimeout: c.WriteTimeout, BufferLimit: c.BufferLimit, RetryWait: c.RetryWait, MaxRetry: c.MaxRetry, TagPrefix: c.TagPrefix, Async: c.AsyncConnect, MarshalAsJSON: c.MarshalAsJSON, SubSecondPrecision: c.SubSecondPrecision, } }
go
func (c Config) FluentConfig() fluent.Config { return fluent.Config{ FluentPort: c.Port, FluentHost: c.Host, FluentNetwork: c.FluentNetwork, FluentSocketPath: c.FluentSocketPath, Timeout: c.Timeout, WriteTimeout: c.WriteTimeout, BufferLimit: c.BufferLimit, RetryWait: c.RetryWait, MaxRetry: c.MaxRetry, TagPrefix: c.TagPrefix, Async: c.AsyncConnect, MarshalAsJSON: c.MarshalAsJSON, SubSecondPrecision: c.SubSecondPrecision, } }
[ "func", "(", "c", "Config", ")", "FluentConfig", "(", ")", "fluent", ".", "Config", "{", "return", "fluent", ".", "Config", "{", "FluentPort", ":", "c", ".", "Port", ",", "FluentHost", ":", "c", ".", "Host", ",", "FluentNetwork", ":", "c", ".", "FluentNetwork", ",", "FluentSocketPath", ":", "c", ".", "FluentSocketPath", ",", "Timeout", ":", "c", ".", "Timeout", ",", "WriteTimeout", ":", "c", ".", "WriteTimeout", ",", "BufferLimit", ":", "c", ".", "BufferLimit", ",", "RetryWait", ":", "c", ".", "RetryWait", ",", "MaxRetry", ":", "c", ".", "MaxRetry", ",", "TagPrefix", ":", "c", ".", "TagPrefix", ",", "Async", ":", "c", ".", "AsyncConnect", ",", "MarshalAsJSON", ":", "c", ".", "MarshalAsJSON", ",", "SubSecondPrecision", ":", "c", ".", "SubSecondPrecision", ",", "}", "\n", "}" ]
// FluentConfig converts data to fluent.Config.
[ "FluentConfig", "converts", "data", "to", "fluent", ".", "Config", "." ]
7275750c56535517a5a7cb7603d40ffcfd0aa144
https://github.com/evalphobia/logrus_fluent/blob/7275750c56535517a5a7cb7603d40ffcfd0aa144/config.go#L37-L53
15,234
gobwas/pool
generic.go
Custom
func Custom(opts ...Option) *Pool { p := &Pool{ pool: make(map[int]*sync.Pool), size: pmath.Identity, } c := (*poolConfig)(p) for _, opt := range opts { opt(c) } return p }
go
func Custom(opts ...Option) *Pool { p := &Pool{ pool: make(map[int]*sync.Pool), size: pmath.Identity, } c := (*poolConfig)(p) for _, opt := range opts { opt(c) } return p }
[ "func", "Custom", "(", "opts", "...", "Option", ")", "*", "Pool", "{", "p", ":=", "&", "Pool", "{", "pool", ":", "make", "(", "map", "[", "int", "]", "*", "sync", ".", "Pool", ")", ",", "size", ":", "pmath", ".", "Identity", ",", "}", "\n\n", "c", ":=", "(", "*", "poolConfig", ")", "(", "p", ")", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "c", ")", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// Custom creates new Pool with given options.
[ "Custom", "creates", "new", "Pool", "with", "given", "options", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/generic.go#L45-L57
15,235
gobwas/pool
generic.go
Put
func (p *Pool) Put(x interface{}, size int) { if pool := p.pool[size]; pool != nil { pool.Put(x) } }
go
func (p *Pool) Put(x interface{}, size int) { if pool := p.pool[size]; pool != nil { pool.Put(x) } }
[ "func", "(", "p", "*", "Pool", ")", "Put", "(", "x", "interface", "{", "}", ",", "size", "int", ")", "{", "if", "pool", ":=", "p", ".", "pool", "[", "size", "]", ";", "pool", "!=", "nil", "{", "pool", ".", "Put", "(", "x", ")", "\n", "}", "\n", "}" ]
// Put takes x and its size for future reuse.
[ "Put", "takes", "x", "and", "its", "size", "for", "future", "reuse", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/generic.go#L71-L75
15,236
gobwas/pool
generic.go
AddSize
func (p *poolConfig) AddSize(n int) { p.pool[n] = new(sync.Pool) }
go
func (p *poolConfig) AddSize(n int) { p.pool[n] = new(sync.Pool) }
[ "func", "(", "p", "*", "poolConfig", ")", "AddSize", "(", "n", "int", ")", "{", "p", ".", "pool", "[", "n", "]", "=", "new", "(", "sync", ".", "Pool", ")", "\n", "}" ]
// AddSize adds size n to the map.
[ "AddSize", "adds", "size", "n", "to", "the", "map", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/generic.go#L80-L82
15,237
gobwas/pool
pbytes/pool.go
GetLen
func (p *Pool) GetLen(n int) []byte { return p.Get(n, n) }
go
func (p *Pool) GetLen(n int) []byte { return p.Get(n, n) }
[ "func", "(", "p", "*", "Pool", ")", "GetLen", "(", "n", "int", ")", "[", "]", "byte", "{", "return", "p", ".", "Get", "(", "n", ",", "n", ")", "\n", "}" ]
// GetLen returns probably reused slice of bytes with at least capacity of n // and exactly len of n.
[ "GetLen", "returns", "probably", "reused", "slice", "of", "bytes", "with", "at", "least", "capacity", "of", "n", "and", "exactly", "len", "of", "n", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/pbytes/pool.go#L57-L59
15,238
gobwas/pool
pbufio/pbufio.go
Get
func (wp *WriterPool) Get(w io.Writer, size int) *bufio.Writer { v, n := wp.pool.Get(size) if v != nil { bw := v.(*bufio.Writer) bw.Reset(w) return bw } return bufio.NewWriterSize(w, n) }
go
func (wp *WriterPool) Get(w io.Writer, size int) *bufio.Writer { v, n := wp.pool.Get(size) if v != nil { bw := v.(*bufio.Writer) bw.Reset(w) return bw } return bufio.NewWriterSize(w, n) }
[ "func", "(", "wp", "*", "WriterPool", ")", "Get", "(", "w", "io", ".", "Writer", ",", "size", "int", ")", "*", "bufio", ".", "Writer", "{", "v", ",", "n", ":=", "wp", ".", "pool", ".", "Get", "(", "size", ")", "\n", "if", "v", "!=", "nil", "{", "bw", ":=", "v", ".", "(", "*", "bufio", ".", "Writer", ")", "\n", "bw", ".", "Reset", "(", "w", ")", "\n", "return", "bw", "\n", "}", "\n", "return", "bufio", ".", "NewWriterSize", "(", "w", ",", "n", ")", "\n", "}" ]
// Get returns bufio.Writer whose buffer has at least size bytes.
[ "Get", "returns", "bufio", ".", "Writer", "whose", "buffer", "has", "at", "least", "size", "bytes", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/pbufio/pbufio.go#L55-L63
15,239
gobwas/pool
pbufio/pbufio.go
Put
func (wp *WriterPool) Put(bw *bufio.Writer) { // Should reset even if we do Reset() inside Get(). // This is done to prevent locking underlying io.Writer from GC. bw.Reset(nil) wp.pool.Put(bw, writerSize(bw)) }
go
func (wp *WriterPool) Put(bw *bufio.Writer) { // Should reset even if we do Reset() inside Get(). // This is done to prevent locking underlying io.Writer from GC. bw.Reset(nil) wp.pool.Put(bw, writerSize(bw)) }
[ "func", "(", "wp", "*", "WriterPool", ")", "Put", "(", "bw", "*", "bufio", ".", "Writer", ")", "{", "// Should reset even if we do Reset() inside Get().", "// This is done to prevent locking underlying io.Writer from GC.", "bw", ".", "Reset", "(", "nil", ")", "\n", "wp", ".", "pool", ".", "Put", "(", "bw", ",", "writerSize", "(", "bw", ")", ")", "\n", "}" ]
// Put takes ownership of bufio.Writer for further reuse.
[ "Put", "takes", "ownership", "of", "bufio", ".", "Writer", "for", "further", "reuse", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/pbufio/pbufio.go#L66-L71
15,240
gobwas/pool
pbufio/pbufio.go
Get
func (rp *ReaderPool) Get(r io.Reader, size int) *bufio.Reader { v, n := rp.pool.Get(size) if v != nil { br := v.(*bufio.Reader) br.Reset(r) return br } return bufio.NewReaderSize(r, n) }
go
func (rp *ReaderPool) Get(r io.Reader, size int) *bufio.Reader { v, n := rp.pool.Get(size) if v != nil { br := v.(*bufio.Reader) br.Reset(r) return br } return bufio.NewReaderSize(r, n) }
[ "func", "(", "rp", "*", "ReaderPool", ")", "Get", "(", "r", "io", ".", "Reader", ",", "size", "int", ")", "*", "bufio", ".", "Reader", "{", "v", ",", "n", ":=", "rp", ".", "pool", ".", "Get", "(", "size", ")", "\n", "if", "v", "!=", "nil", "{", "br", ":=", "v", ".", "(", "*", "bufio", ".", "Reader", ")", "\n", "br", ".", "Reset", "(", "r", ")", "\n", "return", "br", "\n", "}", "\n", "return", "bufio", ".", "NewReaderSize", "(", "r", ",", "n", ")", "\n", "}" ]
// Get returns bufio.Reader whose buffer has at least size bytes.
[ "Get", "returns", "bufio", ".", "Reader", "whose", "buffer", "has", "at", "least", "size", "bytes", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/pbufio/pbufio.go#L90-L98
15,241
gobwas/pool
pbufio/pbufio.go
Put
func (rp *ReaderPool) Put(br *bufio.Reader) { // Should reset even if we do Reset() inside Get(). // This is done to prevent locking underlying io.Reader from GC. br.Reset(nil) rp.pool.Put(br, readerSize(br)) }
go
func (rp *ReaderPool) Put(br *bufio.Reader) { // Should reset even if we do Reset() inside Get(). // This is done to prevent locking underlying io.Reader from GC. br.Reset(nil) rp.pool.Put(br, readerSize(br)) }
[ "func", "(", "rp", "*", "ReaderPool", ")", "Put", "(", "br", "*", "bufio", ".", "Reader", ")", "{", "// Should reset even if we do Reset() inside Get().", "// This is done to prevent locking underlying io.Reader from GC.", "br", ".", "Reset", "(", "nil", ")", "\n", "rp", ".", "pool", ".", "Put", "(", "br", ",", "readerSize", "(", "br", ")", ")", "\n", "}" ]
// Put takes ownership of bufio.Reader for further reuse.
[ "Put", "takes", "ownership", "of", "bufio", ".", "Reader", "for", "further", "reuse", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/pbufio/pbufio.go#L101-L106
15,242
gobwas/pool
internal/pmath/pmath.go
LogarithmicRange
func LogarithmicRange(min, max int, cb func(int)) { if min == 0 { min = 1 } for n := CeilToPowerOfTwo(min); n <= max; n <<= 1 { cb(n) } }
go
func LogarithmicRange(min, max int, cb func(int)) { if min == 0 { min = 1 } for n := CeilToPowerOfTwo(min); n <= max; n <<= 1 { cb(n) } }
[ "func", "LogarithmicRange", "(", "min", ",", "max", "int", ",", "cb", "func", "(", "int", ")", ")", "{", "if", "min", "==", "0", "{", "min", "=", "1", "\n", "}", "\n", "for", "n", ":=", "CeilToPowerOfTwo", "(", "min", ")", ";", "n", "<=", "max", ";", "n", "<<=", "1", "{", "cb", "(", "n", ")", "\n", "}", "\n", "}" ]
// LogarithmicRange iterates from ceiled to power of two min to max, // calling cb on each iteration.
[ "LogarithmicRange", "iterates", "from", "ceiled", "to", "power", "of", "two", "min", "to", "max", "calling", "cb", "on", "each", "iteration", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/internal/pmath/pmath.go#L11-L18
15,243
gobwas/pool
internal/pmath/pmath.go
CeilToPowerOfTwo
func CeilToPowerOfTwo(n int) int { if n&maxintHeadBit != 0 && n > maxintHeadBit { panic("argument is too large") } if n <= 2 { return n } n-- n = fillBits(n) n++ return n }
go
func CeilToPowerOfTwo(n int) int { if n&maxintHeadBit != 0 && n > maxintHeadBit { panic("argument is too large") } if n <= 2 { return n } n-- n = fillBits(n) n++ return n }
[ "func", "CeilToPowerOfTwo", "(", "n", "int", ")", "int", "{", "if", "n", "&", "maxintHeadBit", "!=", "0", "&&", "n", ">", "maxintHeadBit", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "n", "<=", "2", "{", "return", "n", "\n", "}", "\n", "n", "--", "\n", "n", "=", "fillBits", "(", "n", ")", "\n", "n", "++", "\n", "return", "n", "\n", "}" ]
// CeilToPowerOfTwo returns the least power of two integer value greater than // or equal to n.
[ "CeilToPowerOfTwo", "returns", "the", "least", "power", "of", "two", "integer", "value", "greater", "than", "or", "equal", "to", "n", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/internal/pmath/pmath.go#L32-L43
15,244
gobwas/pool
internal/pmath/pmath.go
FloorToPowerOfTwo
func FloorToPowerOfTwo(n int) int { if n <= 2 { return n } n = fillBits(n) n >>= 1 n++ return n }
go
func FloorToPowerOfTwo(n int) int { if n <= 2 { return n } n = fillBits(n) n >>= 1 n++ return n }
[ "func", "FloorToPowerOfTwo", "(", "n", "int", ")", "int", "{", "if", "n", "<=", "2", "{", "return", "n", "\n", "}", "\n", "n", "=", "fillBits", "(", "n", ")", "\n", "n", ">>=", "1", "\n", "n", "++", "\n", "return", "n", "\n", "}" ]
// FloorToPowerOfTwo returns the greatest power of two integer value less than // or equal to n.
[ "FloorToPowerOfTwo", "returns", "the", "greatest", "power", "of", "two", "integer", "value", "less", "than", "or", "equal", "to", "n", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/internal/pmath/pmath.go#L47-L55
15,245
gobwas/pool
pbytes/pool_sanitize.go
Put
func (p *Pool) Put(bts []byte) { hdr := *(*reflect.SliceHeader)(unsafe.Pointer(&bts)) ptr := hdr.Data - uintptr(guardSize) g := (*guard)(unsafe.Pointer(ptr)) if g.magic != magic { panic("unknown slice returned to the pool") } if n := atomic.AddInt32(&g.owners, -1); n < 0 { panic("multiple Put() detected") } // Disable read and write on bytes memory pages. This will cause panic on // incorrect access to returned slice. mprotect(ptr, false, false, g.size) runtime.SetFinalizer(&bts, func(b *[]byte) { mprotect(ptr, true, true, g.size) free(*(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ Data: ptr, Len: g.size, Cap: g.size, }))) }) }
go
func (p *Pool) Put(bts []byte) { hdr := *(*reflect.SliceHeader)(unsafe.Pointer(&bts)) ptr := hdr.Data - uintptr(guardSize) g := (*guard)(unsafe.Pointer(ptr)) if g.magic != magic { panic("unknown slice returned to the pool") } if n := atomic.AddInt32(&g.owners, -1); n < 0 { panic("multiple Put() detected") } // Disable read and write on bytes memory pages. This will cause panic on // incorrect access to returned slice. mprotect(ptr, false, false, g.size) runtime.SetFinalizer(&bts, func(b *[]byte) { mprotect(ptr, true, true, g.size) free(*(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ Data: ptr, Len: g.size, Cap: g.size, }))) }) }
[ "func", "(", "p", "*", "Pool", ")", "Put", "(", "bts", "[", "]", "byte", ")", "{", "hdr", ":=", "*", "(", "*", "reflect", ".", "SliceHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "bts", ")", ")", "\n", "ptr", ":=", "hdr", ".", "Data", "-", "uintptr", "(", "guardSize", ")", "\n\n", "g", ":=", "(", "*", "guard", ")", "(", "unsafe", ".", "Pointer", "(", "ptr", ")", ")", "\n", "if", "g", ".", "magic", "!=", "magic", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "n", ":=", "atomic", ".", "AddInt32", "(", "&", "g", ".", "owners", ",", "-", "1", ")", ";", "n", "<", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Disable read and write on bytes memory pages. This will cause panic on", "// incorrect access to returned slice.", "mprotect", "(", "ptr", ",", "false", ",", "false", ",", "g", ".", "size", ")", "\n\n", "runtime", ".", "SetFinalizer", "(", "&", "bts", ",", "func", "(", "b", "*", "[", "]", "byte", ")", "{", "mprotect", "(", "ptr", ",", "true", ",", "true", ",", "g", ".", "size", ")", "\n", "free", "(", "*", "(", "*", "[", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "reflect", ".", "SliceHeader", "{", "Data", ":", "ptr", ",", "Len", ":", "g", ".", "size", ",", "Cap", ":", "g", ".", "size", ",", "}", ")", ")", ")", "\n", "}", ")", "\n", "}" ]
// Put returns given slice to reuse pool.
[ "Put", "returns", "given", "slice", "to", "reuse", "pool", "." ]
cd2fb0a117357da7830c32f332c8520db8e2827d
https://github.com/gobwas/pool/blob/cd2fb0a117357da7830c32f332c8520db8e2827d/pbytes/pool_sanitize.go#L60-L84
15,246
Gurpartap/logrus-stack
logrus-stack-hook.go
Fire
func (hook LogrusStackHook) Fire(entry *logrus.Entry) error { var skipFrames int if len(entry.Data) == 0 { // When WithField(s) is not used, we have 8 logrus frames to skip. skipFrames = 8 } else { // When WithField(s) is used, we have 6 logrus frames to skip. skipFrames = 6 } var frames stack.Stack // Get the complete stack track past skipFrames count. _frames := stack.Callers(skipFrames) // Remove logrus's own frames that seem to appear after the code is through // certain hoops. e.g. http handler in a separate package. // This is a workaround. for _, frame := range _frames { if !strings.Contains(frame.File, "github.com/sirupsen/logrus") { frames = append(frames, frame) } } if len(frames) > 0 { // If we have a frame, we set it to "caller" field for assigned levels. for _, level := range hook.CallerLevels { if entry.Level == level { entry.Data["caller"] = frames[0] break } } // Set the available frames to "stack" field. for _, level := range hook.StackLevels { if entry.Level == level { entry.Data["stack"] = frames break } } } return nil }
go
func (hook LogrusStackHook) Fire(entry *logrus.Entry) error { var skipFrames int if len(entry.Data) == 0 { // When WithField(s) is not used, we have 8 logrus frames to skip. skipFrames = 8 } else { // When WithField(s) is used, we have 6 logrus frames to skip. skipFrames = 6 } var frames stack.Stack // Get the complete stack track past skipFrames count. _frames := stack.Callers(skipFrames) // Remove logrus's own frames that seem to appear after the code is through // certain hoops. e.g. http handler in a separate package. // This is a workaround. for _, frame := range _frames { if !strings.Contains(frame.File, "github.com/sirupsen/logrus") { frames = append(frames, frame) } } if len(frames) > 0 { // If we have a frame, we set it to "caller" field for assigned levels. for _, level := range hook.CallerLevels { if entry.Level == level { entry.Data["caller"] = frames[0] break } } // Set the available frames to "stack" field. for _, level := range hook.StackLevels { if entry.Level == level { entry.Data["stack"] = frames break } } } return nil }
[ "func", "(", "hook", "LogrusStackHook", ")", "Fire", "(", "entry", "*", "logrus", ".", "Entry", ")", "error", "{", "var", "skipFrames", "int", "\n", "if", "len", "(", "entry", ".", "Data", ")", "==", "0", "{", "// When WithField(s) is not used, we have 8 logrus frames to skip.", "skipFrames", "=", "8", "\n", "}", "else", "{", "// When WithField(s) is used, we have 6 logrus frames to skip.", "skipFrames", "=", "6", "\n", "}", "\n\n", "var", "frames", "stack", ".", "Stack", "\n\n", "// Get the complete stack track past skipFrames count.", "_frames", ":=", "stack", ".", "Callers", "(", "skipFrames", ")", "\n\n", "// Remove logrus's own frames that seem to appear after the code is through", "// certain hoops. e.g. http handler in a separate package.", "// This is a workaround.", "for", "_", ",", "frame", ":=", "range", "_frames", "{", "if", "!", "strings", ".", "Contains", "(", "frame", ".", "File", ",", "\"", "\"", ")", "{", "frames", "=", "append", "(", "frames", ",", "frame", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "frames", ")", ">", "0", "{", "// If we have a frame, we set it to \"caller\" field for assigned levels.", "for", "_", ",", "level", ":=", "range", "hook", ".", "CallerLevels", "{", "if", "entry", ".", "Level", "==", "level", "{", "entry", ".", "Data", "[", "\"", "\"", "]", "=", "frames", "[", "0", "]", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// Set the available frames to \"stack\" field.", "for", "_", ",", "level", ":=", "range", "hook", ".", "StackLevels", "{", "if", "entry", ".", "Level", "==", "level", "{", "entry", ".", "Data", "[", "\"", "\"", "]", "=", "frames", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Fire is called by logrus when something is logged.
[ "Fire", "is", "called", "by", "logrus", "when", "something", "is", "logged", "." ]
89c00d8a28f43c567d92eb81a2945301a6a9fbb9
https://github.com/Gurpartap/logrus-stack/blob/89c00d8a28f43c567d92eb81a2945301a6a9fbb9/logrus-stack-hook.go#L47-L90
15,247
dimchansky/utfbom
utfbom.go
String
func (e Encoding) String() string { switch e { case UTF8: return "UTF8" case UTF16BigEndian: return "UTF16BigEndian" case UTF16LittleEndian: return "UTF16LittleEndian" case UTF32BigEndian: return "UTF32BigEndian" case UTF32LittleEndian: return "UTF32LittleEndian" default: return "Unknown" } }
go
func (e Encoding) String() string { switch e { case UTF8: return "UTF8" case UTF16BigEndian: return "UTF16BigEndian" case UTF16LittleEndian: return "UTF16LittleEndian" case UTF32BigEndian: return "UTF32BigEndian" case UTF32LittleEndian: return "UTF32LittleEndian" default: return "Unknown" } }
[ "func", "(", "e", "Encoding", ")", "String", "(", ")", "string", "{", "switch", "e", "{", "case", "UTF8", ":", "return", "\"", "\"", "\n", "case", "UTF16BigEndian", ":", "return", "\"", "\"", "\n", "case", "UTF16LittleEndian", ":", "return", "\"", "\"", "\n", "case", "UTF32BigEndian", ":", "return", "\"", "\"", "\n", "case", "UTF32LittleEndian", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// String returns a user-friendly string representation of the encoding. Satisfies fmt.Stringer interface.
[ "String", "returns", "a", "user", "-", "friendly", "string", "representation", "of", "the", "encoding", ".", "Satisfies", "fmt", ".", "Stringer", "interface", "." ]
d2133a1ce379ef6fa992b0514a77146c60db9d1c
https://github.com/dimchansky/utfbom/blob/d2133a1ce379ef6fa992b0514a77146c60db9d1c/utfbom.go#L36-L51
15,248
dimchansky/utfbom
utfbom.go
Read
func (r *Reader) Read(p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } if r.buf == nil { if r.err != nil { return 0, r.readErr() } return r.rd.Read(p) } // copy as much as we can n = copy(p, r.buf) r.buf = nilIfEmpty(r.buf[n:]) return n, nil }
go
func (r *Reader) Read(p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } if r.buf == nil { if r.err != nil { return 0, r.readErr() } return r.rd.Read(p) } // copy as much as we can n = copy(p, r.buf) r.buf = nilIfEmpty(r.buf[n:]) return n, nil }
[ "func", "(", "r", "*", "Reader", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n\n", "if", "r", ".", "buf", "==", "nil", "{", "if", "r", ".", "err", "!=", "nil", "{", "return", "0", ",", "r", ".", "readErr", "(", ")", "\n", "}", "\n\n", "return", "r", ".", "rd", ".", "Read", "(", "p", ")", "\n", "}", "\n\n", "// copy as much as we can", "n", "=", "copy", "(", "p", ",", "r", ".", "buf", ")", "\n", "r", ".", "buf", "=", "nilIfEmpty", "(", "r", ".", "buf", "[", "n", ":", "]", ")", "\n", "return", "n", ",", "nil", "\n", "}" ]
// Read is an implementation of io.Reader interface. // The bytes are taken from the underlying Reader, but it checks for BOMs, removing them as necessary.
[ "Read", "is", "an", "implementation", "of", "io", ".", "Reader", "interface", ".", "The", "bytes", "are", "taken", "from", "the", "underlying", "Reader", "but", "it", "checks", "for", "BOMs", "removing", "them", "as", "necessary", "." ]
d2133a1ce379ef6fa992b0514a77146c60db9d1c
https://github.com/dimchansky/utfbom/blob/d2133a1ce379ef6fa992b0514a77146c60db9d1c/utfbom.go#L89-L106
15,249
FactomProject/factom
chain.go
ComposeChainCommit
func ComposeChainCommit(c *Chain, ec *ECAddress) (*JSON2Request, error) { buf := new(bytes.Buffer) // 1 byte version buf.Write([]byte{0}) // 6 byte milliTimestamp buf.Write(milliTime()) e := c.FirstEntry // 32 byte ChainID Hash if p, err := hex.DecodeString(c.ChainID); err != nil { return nil, err } else { // double sha256 hash of ChainID buf.Write(shad(p)) } // 32 byte Weld; sha256(sha256(EntryHash + ChainID)) if cid, err := hex.DecodeString(c.ChainID); err != nil { return nil, err } else { s := append(e.Hash(), cid...) buf.Write(shad(s)) } // 32 byte Entry Hash of the First Entry buf.Write(e.Hash()) // 1 byte number of Entry Credits to pay if d, err := EntryCost(e); err != nil { return nil, err } else { buf.WriteByte(byte(d + 10)) } // 32 byte Entry Credit Address Public Key + 64 byte Signature sig := ec.Sign(buf.Bytes()) buf.Write(ec.PubBytes()) buf.Write(sig[:]) params := messageRequest{Message: hex.EncodeToString(buf.Bytes())} req := NewJSON2Request("commit-chain", APICounter(), params) return req, nil }
go
func ComposeChainCommit(c *Chain, ec *ECAddress) (*JSON2Request, error) { buf := new(bytes.Buffer) // 1 byte version buf.Write([]byte{0}) // 6 byte milliTimestamp buf.Write(milliTime()) e := c.FirstEntry // 32 byte ChainID Hash if p, err := hex.DecodeString(c.ChainID); err != nil { return nil, err } else { // double sha256 hash of ChainID buf.Write(shad(p)) } // 32 byte Weld; sha256(sha256(EntryHash + ChainID)) if cid, err := hex.DecodeString(c.ChainID); err != nil { return nil, err } else { s := append(e.Hash(), cid...) buf.Write(shad(s)) } // 32 byte Entry Hash of the First Entry buf.Write(e.Hash()) // 1 byte number of Entry Credits to pay if d, err := EntryCost(e); err != nil { return nil, err } else { buf.WriteByte(byte(d + 10)) } // 32 byte Entry Credit Address Public Key + 64 byte Signature sig := ec.Sign(buf.Bytes()) buf.Write(ec.PubBytes()) buf.Write(sig[:]) params := messageRequest{Message: hex.EncodeToString(buf.Bytes())} req := NewJSON2Request("commit-chain", APICounter(), params) return req, nil }
[ "func", "ComposeChainCommit", "(", "c", "*", "Chain", ",", "ec", "*", "ECAddress", ")", "(", "*", "JSON2Request", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "// 1 byte version", "buf", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n\n", "// 6 byte milliTimestamp", "buf", ".", "Write", "(", "milliTime", "(", ")", ")", "\n\n", "e", ":=", "c", ".", "FirstEntry", "\n\n", "// 32 byte ChainID Hash", "if", "p", ",", "err", ":=", "hex", ".", "DecodeString", "(", "c", ".", "ChainID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "// double sha256 hash of ChainID", "buf", ".", "Write", "(", "shad", "(", "p", ")", ")", "\n", "}", "\n\n", "// 32 byte Weld; sha256(sha256(EntryHash + ChainID))", "if", "cid", ",", "err", ":=", "hex", ".", "DecodeString", "(", "c", ".", "ChainID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "s", ":=", "append", "(", "e", ".", "Hash", "(", ")", ",", "cid", "...", ")", "\n", "buf", ".", "Write", "(", "shad", "(", "s", ")", ")", "\n", "}", "\n\n", "// 32 byte Entry Hash of the First Entry", "buf", ".", "Write", "(", "e", ".", "Hash", "(", ")", ")", "\n\n", "// 1 byte number of Entry Credits to pay", "if", "d", ",", "err", ":=", "EntryCost", "(", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "buf", ".", "WriteByte", "(", "byte", "(", "d", "+", "10", ")", ")", "\n", "}", "\n\n", "// 32 byte Entry Credit Address Public Key + 64 byte Signature", "sig", ":=", "ec", ".", "Sign", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "buf", ".", "Write", "(", "ec", ".", "PubBytes", "(", ")", ")", "\n", "buf", ".", "Write", "(", "sig", "[", ":", "]", ")", "\n\n", "params", ":=", "messageRequest", "{", "Message", ":", "hex", ".", "EncodeToString", "(", "buf", ".", "Bytes", "(", ")", ")", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// ComposeChainCommit creates a JSON2Request to commit a new Chain via the // factomd web api. The request includes the marshaled MessageRequest with the // Entry Credit Signature.
[ "ComposeChainCommit", "creates", "a", "JSON2Request", "to", "commit", "a", "new", "Chain", "via", "the", "factomd", "web", "api", ".", "The", "request", "includes", "the", "marshaled", "MessageRequest", "with", "the", "Entry", "Credit", "Signature", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/chain.go#L48-L94
15,250
FactomProject/factom
chain.go
ComposeChainReveal
func ComposeChainReveal(c *Chain) (*JSON2Request, error) { p, err := c.FirstEntry.MarshalBinary() if err != nil { return nil, err } params := entryRequest{Entry: hex.EncodeToString(p)} req := NewJSON2Request("reveal-chain", APICounter(), params) return req, nil }
go
func ComposeChainReveal(c *Chain) (*JSON2Request, error) { p, err := c.FirstEntry.MarshalBinary() if err != nil { return nil, err } params := entryRequest{Entry: hex.EncodeToString(p)} req := NewJSON2Request("reveal-chain", APICounter(), params) return req, nil }
[ "func", "ComposeChainReveal", "(", "c", "*", "Chain", ")", "(", "*", "JSON2Request", ",", "error", ")", "{", "p", ",", "err", ":=", "c", ".", "FirstEntry", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "params", ":=", "entryRequest", "{", "Entry", ":", "hex", ".", "EncodeToString", "(", "p", ")", "}", "\n\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n", "return", "req", ",", "nil", "\n", "}" ]
// ComposeChainReveal creates a JSON2Request to reveal the Chain via the factomd // web api.
[ "ComposeChainReveal", "creates", "a", "JSON2Request", "to", "reveal", "the", "Chain", "via", "the", "factomd", "web", "api", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/chain.go#L98-L107
15,251
FactomProject/factom
chain.go
CommitChain
func CommitChain(c *Chain, ec *ECAddress) (string, error) { type commitResponse struct { Message string `json:"message"` TxID string `json:"txid"` } req, err := ComposeChainCommit(c, ec) if err != nil { return "", err } resp, err := factomdRequest(req) if err != nil { return "", err } if resp.Error != nil { return "", resp.Error } r := new(commitResponse) if err := json.Unmarshal(resp.JSONResult(), r); err != nil { return "", err } return r.TxID, nil }
go
func CommitChain(c *Chain, ec *ECAddress) (string, error) { type commitResponse struct { Message string `json:"message"` TxID string `json:"txid"` } req, err := ComposeChainCommit(c, ec) if err != nil { return "", err } resp, err := factomdRequest(req) if err != nil { return "", err } if resp.Error != nil { return "", resp.Error } r := new(commitResponse) if err := json.Unmarshal(resp.JSONResult(), r); err != nil { return "", err } return r.TxID, nil }
[ "func", "CommitChain", "(", "c", "*", "Chain", ",", "ec", "*", "ECAddress", ")", "(", "string", ",", "error", ")", "{", "type", "commitResponse", "struct", "{", "Message", "string", "`json:\"message\"`", "\n", "TxID", "string", "`json:\"txid\"`", "\n", "}", "\n\n", "req", ",", "err", ":=", "ComposeChainCommit", "(", "c", ",", "ec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "factomdRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "\"", "\"", ",", "resp", ".", "Error", "\n", "}", "\n", "r", ":=", "new", "(", "commitResponse", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "r", ".", "TxID", ",", "nil", "\n", "}" ]
// CommitChain sends the signed ChainID, the Entry Hash, and the Entry Credit // public key to the factom network. Once the payment is verified and the // network is commited to publishing the Chain it may be published by revealing // the First Entry in the Chain.
[ "CommitChain", "sends", "the", "signed", "ChainID", "the", "Entry", "Hash", "and", "the", "Entry", "Credit", "public", "key", "to", "the", "factom", "network", ".", "Once", "the", "payment", "is", "verified", "and", "the", "network", "is", "commited", "to", "publishing", "the", "Chain", "it", "may", "be", "published", "by", "revealing", "the", "First", "Entry", "in", "the", "Chain", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/chain.go#L113-L137
15,252
FactomProject/factom
wallet/transaction.go
SignTransaction
func (w *Wallet) SignTransaction(name string, force bool) error { tx, err := w.GetTransaction(name) if err != nil { return err } if force == false { // check that the address balances are sufficient for the transaction if err := checkCovered(tx); err != nil { return err } // check that the fee is being paid (and not overpaid) if err := checkFee(tx); err != nil { return err } } data, err := tx.MarshalBinarySig() if err != nil { return err } rcds := tx.GetRCDs() if len(rcds) == 0 { return ErrTXNoInputs } for i, rcd := range rcds { a, err := rcd.GetAddress() if err != nil { return err } f, err := w.GetFCTAddress(primitives.ConvertFctAddressToUserStr(a)) if err != nil { return err } sig := factoid.NewSingleSignatureBlock(f.SecBytes(), data) tx.SetSignatureBlock(i, sig) } return nil }
go
func (w *Wallet) SignTransaction(name string, force bool) error { tx, err := w.GetTransaction(name) if err != nil { return err } if force == false { // check that the address balances are sufficient for the transaction if err := checkCovered(tx); err != nil { return err } // check that the fee is being paid (and not overpaid) if err := checkFee(tx); err != nil { return err } } data, err := tx.MarshalBinarySig() if err != nil { return err } rcds := tx.GetRCDs() if len(rcds) == 0 { return ErrTXNoInputs } for i, rcd := range rcds { a, err := rcd.GetAddress() if err != nil { return err } f, err := w.GetFCTAddress(primitives.ConvertFctAddressToUserStr(a)) if err != nil { return err } sig := factoid.NewSingleSignatureBlock(f.SecBytes(), data) tx.SetSignatureBlock(i, sig) } return nil }
[ "func", "(", "w", "*", "Wallet", ")", "SignTransaction", "(", "name", "string", ",", "force", "bool", ")", "error", "{", "tx", ",", "err", ":=", "w", ".", "GetTransaction", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "force", "==", "false", "{", "// check that the address balances are sufficient for the transaction", "if", "err", ":=", "checkCovered", "(", "tx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// check that the fee is being paid (and not overpaid)", "if", "err", ":=", "checkFee", "(", "tx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "data", ",", "err", ":=", "tx", ".", "MarshalBinarySig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "rcds", ":=", "tx", ".", "GetRCDs", "(", ")", "\n", "if", "len", "(", "rcds", ")", "==", "0", "{", "return", "ErrTXNoInputs", "\n", "}", "\n", "for", "i", ",", "rcd", ":=", "range", "rcds", "{", "a", ",", "err", ":=", "rcd", ".", "GetAddress", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "f", ",", "err", ":=", "w", ".", "GetFCTAddress", "(", "primitives", ".", "ConvertFctAddressToUserStr", "(", "a", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sig", ":=", "factoid", ".", "NewSingleSignatureBlock", "(", "f", ".", "SecBytes", "(", ")", ",", "data", ")", "\n", "tx", ".", "SetSignatureBlock", "(", "i", ",", "sig", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SignTransaction signs a tmp transaction in the wallet with the appropriate // keys from the wallet db // force=true ignores the existing balance and fee overpayment checks.
[ "SignTransaction", "signs", "a", "tmp", "transaction", "in", "the", "wallet", "with", "the", "appropriate", "keys", "from", "the", "wallet", "db", "force", "=", "true", "ignores", "the", "existing", "balance", "and", "fee", "overpayment", "checks", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/transaction.go#L247-L289
15,253
FactomProject/factom
addresses.go
Sign
func (a *ECAddress) Sign(msg []byte) *[ed.SignatureSize]byte { return ed.Sign(a.SecFixed(), msg) }
go
func (a *ECAddress) Sign(msg []byte) *[ed.SignatureSize]byte { return ed.Sign(a.SecFixed(), msg) }
[ "func", "(", "a", "*", "ECAddress", ")", "Sign", "(", "msg", "[", "]", "byte", ")", "*", "[", "ed", ".", "SignatureSize", "]", "byte", "{", "return", "ed", ".", "Sign", "(", "a", ".", "SecFixed", "(", ")", ",", "msg", ")", "\n", "}" ]
// Sign the message with the ECAddress private key
[ "Sign", "the", "message", "with", "the", "ECAddress", "private", "key" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/addresses.go#L224-L226
15,254
FactomProject/factom
addresses.go
MakeFactoidAddressFromKoinify
func MakeFactoidAddressFromKoinify(mnemonic string) (*FactoidAddress, error) { mnemonic, err := ParseAndValidateMnemonic(mnemonic) if err != nil { return nil, err } seed, err := bip39.NewSeedWithErrorChecking(mnemonic, "") if err != nil { return nil, err } masterKey, err := bip32.NewMasterKey(seed) if err != nil { return nil, err } child, err := masterKey.NewChildKey(bip32.FirstHardenedChild + 7) if err != nil { return nil, err } return MakeFactoidAddress(child.Key) }
go
func MakeFactoidAddressFromKoinify(mnemonic string) (*FactoidAddress, error) { mnemonic, err := ParseAndValidateMnemonic(mnemonic) if err != nil { return nil, err } seed, err := bip39.NewSeedWithErrorChecking(mnemonic, "") if err != nil { return nil, err } masterKey, err := bip32.NewMasterKey(seed) if err != nil { return nil, err } child, err := masterKey.NewChildKey(bip32.FirstHardenedChild + 7) if err != nil { return nil, err } return MakeFactoidAddress(child.Key) }
[ "func", "MakeFactoidAddressFromKoinify", "(", "mnemonic", "string", ")", "(", "*", "FactoidAddress", ",", "error", ")", "{", "mnemonic", ",", "err", ":=", "ParseAndValidateMnemonic", "(", "mnemonic", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "seed", ",", "err", ":=", "bip39", ".", "NewSeedWithErrorChecking", "(", "mnemonic", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "masterKey", ",", "err", ":=", "bip32", ".", "NewMasterKey", "(", "seed", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "child", ",", "err", ":=", "masterKey", ".", "NewChildKey", "(", "bip32", ".", "FirstHardenedChild", "+", "7", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "MakeFactoidAddress", "(", "child", ".", "Key", ")", "\n", "}" ]
// MakeFactoidAddressFromKoinify takes the 12 word string used in the Koinify // sale and returns a Factoid Address.
[ "MakeFactoidAddressFromKoinify", "takes", "the", "12", "word", "string", "used", "in", "the", "Koinify", "sale", "and", "returns", "a", "Factoid", "Address", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/addresses.go#L327-L347
15,255
FactomProject/factom
identity.go
GetIdentityChainID
func GetIdentityChainID(name []string) string { hs := sha256.New() for _, part := range name { h := sha256.Sum256([]byte(part)) hs.Write(h[:]) } return hex.EncodeToString(hs.Sum(nil)) }
go
func GetIdentityChainID(name []string) string { hs := sha256.New() for _, part := range name { h := sha256.Sum256([]byte(part)) hs.Write(h[:]) } return hex.EncodeToString(hs.Sum(nil)) }
[ "func", "GetIdentityChainID", "(", "name", "[", "]", "string", ")", "string", "{", "hs", ":=", "sha256", ".", "New", "(", ")", "\n", "for", "_", ",", "part", ":=", "range", "name", "{", "h", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "part", ")", ")", "\n", "hs", ".", "Write", "(", "h", "[", ":", "]", ")", "\n", "}", "\n", "return", "hex", ".", "EncodeToString", "(", "hs", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// GetIdentityChainID takes an identity name and returns its corresponding ChainID
[ "GetIdentityChainID", "takes", "an", "identity", "name", "and", "returns", "its", "corresponding", "ChainID" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/identity.go#L28-L35
15,256
FactomProject/factom
identityKeys.go
GetIdentityKey
func GetIdentityKey(s string) (*IdentityKey, error) { if !IsValidIdentityKey(s) { return nil, fmt.Errorf("invalid Identity Private Key") } p := base58.Decode(s) if !bytes.Equal(p[:IDKeyPrefixLength], idSecPrefix) { return nil, fmt.Errorf("invalid Identity Private Key") } return MakeIdentityKey(p[IDKeyPrefixLength:IDKeyBodyLength]) }
go
func GetIdentityKey(s string) (*IdentityKey, error) { if !IsValidIdentityKey(s) { return nil, fmt.Errorf("invalid Identity Private Key") } p := base58.Decode(s) if !bytes.Equal(p[:IDKeyPrefixLength], idSecPrefix) { return nil, fmt.Errorf("invalid Identity Private Key") } return MakeIdentityKey(p[IDKeyPrefixLength:IDKeyBodyLength]) }
[ "func", "GetIdentityKey", "(", "s", "string", ")", "(", "*", "IdentityKey", ",", "error", ")", "{", "if", "!", "IsValidIdentityKey", "(", "s", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ":=", "base58", ".", "Decode", "(", "s", ")", "\n\n", "if", "!", "bytes", ".", "Equal", "(", "p", "[", ":", "IDKeyPrefixLength", "]", ",", "idSecPrefix", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "MakeIdentityKey", "(", "p", "[", "IDKeyPrefixLength", ":", "IDKeyBodyLength", "]", ")", "\n", "}" ]
// GetIdentityKey takes a private key string and returns an IdentityKey.
[ "GetIdentityKey", "takes", "a", "private", "key", "string", "and", "returns", "an", "IdentityKey", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/identityKeys.go#L120-L131
15,257
FactomProject/factom
identityKeys.go
Sign
func (k *IdentityKey) Sign(msg []byte) *[ed.SignatureSize]byte { return ed.Sign(k.SecFixed(), msg) }
go
func (k *IdentityKey) Sign(msg []byte) *[ed.SignatureSize]byte { return ed.Sign(k.SecFixed(), msg) }
[ "func", "(", "k", "*", "IdentityKey", ")", "Sign", "(", "msg", "[", "]", "byte", ")", "*", "[", "ed", ".", "SignatureSize", "]", "byte", "{", "return", "ed", ".", "Sign", "(", "k", ".", "SecFixed", "(", ")", ",", "msg", ")", "\n", "}" ]
// Sign the message with the Identity private key
[ "Sign", "the", "message", "with", "the", "Identity", "private", "key" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/identityKeys.go#L207-L209
15,258
FactomProject/factom
wallet/txdatabase.go
GetAllTXs
func (db *TXDatabaseOverlay) GetAllTXs() ([]interfaces.ITransaction, error) { // update the database and get the newest fblock _, err := db.update() if err != nil { return nil, err } fblock, err := db.DBO.FetchFBlockHead() if err != nil { return nil, err } if fblock == nil { return nil, fmt.Errorf("FBlock Chain has not finished syncing") } txs := make([]interfaces.ITransaction, 0) for { // get all of the txs from the block height := fblock.GetDatabaseHeight() for _, tx := range fblock.GetTransactions() { ins, err := tx.TotalInputs() if err != nil { return nil, err } outs, err := tx.TotalOutputs() if err != nil { return nil, err } if ins != 0 || outs != 0 { tx.SetBlockHeight(height) txs = append(txs, tx) } } if pre := fblock.GetPrevKeyMR().String(); pre != factom.ZeroHash { // get the previous block fblock, err = db.GetFBlock(pre) if err != nil { return nil, err } else if fblock == nil { return nil, fmt.Errorf("Missing fblock in database: %s", pre) } } else { break } } return txs, nil }
go
func (db *TXDatabaseOverlay) GetAllTXs() ([]interfaces.ITransaction, error) { // update the database and get the newest fblock _, err := db.update() if err != nil { return nil, err } fblock, err := db.DBO.FetchFBlockHead() if err != nil { return nil, err } if fblock == nil { return nil, fmt.Errorf("FBlock Chain has not finished syncing") } txs := make([]interfaces.ITransaction, 0) for { // get all of the txs from the block height := fblock.GetDatabaseHeight() for _, tx := range fblock.GetTransactions() { ins, err := tx.TotalInputs() if err != nil { return nil, err } outs, err := tx.TotalOutputs() if err != nil { return nil, err } if ins != 0 || outs != 0 { tx.SetBlockHeight(height) txs = append(txs, tx) } } if pre := fblock.GetPrevKeyMR().String(); pre != factom.ZeroHash { // get the previous block fblock, err = db.GetFBlock(pre) if err != nil { return nil, err } else if fblock == nil { return nil, fmt.Errorf("Missing fblock in database: %s", pre) } } else { break } } return txs, nil }
[ "func", "(", "db", "*", "TXDatabaseOverlay", ")", "GetAllTXs", "(", ")", "(", "[", "]", "interfaces", ".", "ITransaction", ",", "error", ")", "{", "// update the database and get the newest fblock", "_", ",", "err", ":=", "db", ".", "update", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fblock", ",", "err", ":=", "db", ".", "DBO", ".", "FetchFBlockHead", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "fblock", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "txs", ":=", "make", "(", "[", "]", "interfaces", ".", "ITransaction", ",", "0", ")", "\n\n", "for", "{", "// get all of the txs from the block", "height", ":=", "fblock", ".", "GetDatabaseHeight", "(", ")", "\n", "for", "_", ",", "tx", ":=", "range", "fblock", ".", "GetTransactions", "(", ")", "{", "ins", ",", "err", ":=", "tx", ".", "TotalInputs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "outs", ",", "err", ":=", "tx", ".", "TotalOutputs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "ins", "!=", "0", "||", "outs", "!=", "0", "{", "tx", ".", "SetBlockHeight", "(", "height", ")", "\n", "txs", "=", "append", "(", "txs", ",", "tx", ")", "\n", "}", "\n", "}", "\n\n", "if", "pre", ":=", "fblock", ".", "GetPrevKeyMR", "(", ")", ".", "String", "(", ")", ";", "pre", "!=", "factom", ".", "ZeroHash", "{", "// get the previous block", "fblock", ",", "err", "=", "db", ".", "GetFBlock", "(", "pre", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "fblock", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pre", ")", "\n", "}", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "txs", ",", "nil", "\n", "}" ]
// GetAllTXs returns a list of all transactions in the history of Factom. A // local database is used to cache the factoid blocks.
[ "GetAllTXs", "returns", "a", "list", "of", "all", "transactions", "in", "the", "history", "of", "Factom", ".", "A", "local", "database", "is", "used", "to", "cache", "the", "factoid", "blocks", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/txdatabase.go#L93-L141
15,259
FactomProject/factom
wallet/txdatabase.go
GetTX
func (db *TXDatabaseOverlay) GetTX(txid string) (interfaces.ITransaction, error) { txs, err := db.GetAllTXs() if err != nil { return nil, err } for _, tx := range txs { if tx.GetSigHash().String() == txid { return tx, nil } } return nil, fmt.Errorf("Transaction not found") }
go
func (db *TXDatabaseOverlay) GetTX(txid string) (interfaces.ITransaction, error) { txs, err := db.GetAllTXs() if err != nil { return nil, err } for _, tx := range txs { if tx.GetSigHash().String() == txid { return tx, nil } } return nil, fmt.Errorf("Transaction not found") }
[ "func", "(", "db", "*", "TXDatabaseOverlay", ")", "GetTX", "(", "txid", "string", ")", "(", "interfaces", ".", "ITransaction", ",", "error", ")", "{", "txs", ",", "err", ":=", "db", ".", "GetAllTXs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "tx", ":=", "range", "txs", "{", "if", "tx", ".", "GetSigHash", "(", ")", ".", "String", "(", ")", "==", "txid", "{", "return", "tx", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// GetTX gets a transaction by the transaction id
[ "GetTX", "gets", "a", "transaction", "by", "the", "transaction", "id" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/txdatabase.go#L144-L157
15,260
FactomProject/factom
wallet/txdatabase.go
GetTXAddress
func (db *TXDatabaseOverlay) GetTXAddress(adr string) ( []interfaces.ITransaction, error) { filtered := make([]interfaces.ITransaction, 0) txs, err := db.GetAllTXs() if err != nil { return nil, err } if factom.AddressStringType(adr) == factom.FactoidPub { for _, tx := range txs { for _, in := range tx.GetInputs() { if primitives.ConvertFctAddressToUserStr(in.GetAddress()) == adr { filtered = append(filtered, tx) } } for _, out := range tx.GetOutputs() { if primitives.ConvertFctAddressToUserStr(out.GetAddress()) == adr { filtered = append(filtered, tx) } } } } else if factom.AddressStringType(adr) == factom.ECPub { for _, tx := range txs { for _, out := range tx.GetECOutputs() { if primitives.ConvertECAddressToUserStr(out.GetAddress()) == adr { filtered = append(filtered, tx) } } } } else { return nil, fmt.Errorf("not a valid address") } return filtered, nil }
go
func (db *TXDatabaseOverlay) GetTXAddress(adr string) ( []interfaces.ITransaction, error) { filtered := make([]interfaces.ITransaction, 0) txs, err := db.GetAllTXs() if err != nil { return nil, err } if factom.AddressStringType(adr) == factom.FactoidPub { for _, tx := range txs { for _, in := range tx.GetInputs() { if primitives.ConvertFctAddressToUserStr(in.GetAddress()) == adr { filtered = append(filtered, tx) } } for _, out := range tx.GetOutputs() { if primitives.ConvertFctAddressToUserStr(out.GetAddress()) == adr { filtered = append(filtered, tx) } } } } else if factom.AddressStringType(adr) == factom.ECPub { for _, tx := range txs { for _, out := range tx.GetECOutputs() { if primitives.ConvertECAddressToUserStr(out.GetAddress()) == adr { filtered = append(filtered, tx) } } } } else { return nil, fmt.Errorf("not a valid address") } return filtered, nil }
[ "func", "(", "db", "*", "TXDatabaseOverlay", ")", "GetTXAddress", "(", "adr", "string", ")", "(", "[", "]", "interfaces", ".", "ITransaction", ",", "error", ")", "{", "filtered", ":=", "make", "(", "[", "]", "interfaces", ".", "ITransaction", ",", "0", ")", "\n\n", "txs", ",", "err", ":=", "db", ".", "GetAllTXs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "factom", ".", "AddressStringType", "(", "adr", ")", "==", "factom", ".", "FactoidPub", "{", "for", "_", ",", "tx", ":=", "range", "txs", "{", "for", "_", ",", "in", ":=", "range", "tx", ".", "GetInputs", "(", ")", "{", "if", "primitives", ".", "ConvertFctAddressToUserStr", "(", "in", ".", "GetAddress", "(", ")", ")", "==", "adr", "{", "filtered", "=", "append", "(", "filtered", ",", "tx", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "out", ":=", "range", "tx", ".", "GetOutputs", "(", ")", "{", "if", "primitives", ".", "ConvertFctAddressToUserStr", "(", "out", ".", "GetAddress", "(", ")", ")", "==", "adr", "{", "filtered", "=", "append", "(", "filtered", ",", "tx", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "if", "factom", ".", "AddressStringType", "(", "adr", ")", "==", "factom", ".", "ECPub", "{", "for", "_", ",", "tx", ":=", "range", "txs", "{", "for", "_", ",", "out", ":=", "range", "tx", ".", "GetECOutputs", "(", ")", "{", "if", "primitives", ".", "ConvertECAddressToUserStr", "(", "out", ".", "GetAddress", "(", ")", ")", "==", "adr", "{", "filtered", "=", "append", "(", "filtered", ",", "tx", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "filtered", ",", "nil", "\n", "}" ]
// GetTXAddress returns a list of all transactions in the history of Factom that // include a specific address.
[ "GetTXAddress", "returns", "a", "list", "of", "all", "transactions", "in", "the", "history", "of", "Factom", "that", "include", "a", "specific", "address", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/txdatabase.go#L161-L196
15,261
FactomProject/factom
wallet/txdatabase.go
GetFBlock
func (db *TXDatabaseOverlay) GetFBlock(keymr string) (interfaces.IFBlock, error) { h, err := primitives.NewShaHashFromStr(keymr) if err != nil { return nil, err } fBlock, err := db.DBO.FetchFBlock(h) if err != nil { return nil, err } return fBlock, nil }
go
func (db *TXDatabaseOverlay) GetFBlock(keymr string) (interfaces.IFBlock, error) { h, err := primitives.NewShaHashFromStr(keymr) if err != nil { return nil, err } fBlock, err := db.DBO.FetchFBlock(h) if err != nil { return nil, err } return fBlock, nil }
[ "func", "(", "db", "*", "TXDatabaseOverlay", ")", "GetFBlock", "(", "keymr", "string", ")", "(", "interfaces", ".", "IFBlock", ",", "error", ")", "{", "h", ",", "err", ":=", "primitives", ".", "NewShaHashFromStr", "(", "keymr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fBlock", ",", "err", ":=", "db", ".", "DBO", ".", "FetchFBlock", "(", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "fBlock", ",", "nil", "\n", "}" ]
// GetFBlock retrives a Factoid Block from Factom
[ "GetFBlock", "retrives", "a", "Factoid", "Block", "from", "Factom" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/txdatabase.go#L260-L271
15,262
FactomProject/factom
wallet/txdatabase.go
update
func (db *TXDatabaseOverlay) update() (string, error) { newestFBlock, err := fblockHead() if err != nil { return "", err } start, err := db.FetchNextFBlockHeight() if err != nil { return "", err } // Make sure we didn't switch networks genesis, err := db.DBO.FetchFBlockByHeight(0) if err != nil { return "", err } if genesis != nil { genesis2, err := getdblockbyheight(0) if err != nil { return "", err } var gensisFBlockKeyMr interfaces.IHash for _, e := range genesis2.GetDBEntries() { if e.GetChainID().String() == "000000000000000000000000000000000000000000000000000000000000000f" { gensisFBlockKeyMr = e.GetKeyMR() break } } if gensisFBlockKeyMr == nil { return "", fmt.Errorf("unable to fetch the genesis block via the api") } if !gensisFBlockKeyMr.IsSameAs(genesis.GetKeyMR()) { start = 0 } } newestHeight := newestFBlock.GetDatabaseHeight() // If the newest block in the tx cashe has a greater height than the newest // fblock then clear the cashe and start from 0. if start >= newestHeight { return newestFBlock.GetKeyMR().String(), nil } db.DBO.StartMultiBatch() for i := start; i <= newestHeight; i++ { if i%1000 == 0 { if newestHeight-start > 1000 { fmt.Printf("Fetching block %v/%v\n", i, newestHeight) } } fblock, err := getfblockbyheight(i) if err != nil { db.DBO.ExecuteMultiBatch() return "", err } db.DBO.ProcessFBlockMultiBatch(fblock) // Save to DB every 500 blocks if i%500 == 0 { db.DBO.ExecuteMultiBatch() db.DBO.StartMultiBatch() } // If the wallet is stopped, this process becomes hard to kill. Have it exit if db.quit { break } } if !db.quit { fmt.Printf("Fetching block %v/%v\n", newestHeight, newestHeight) } // Save the remaining blocks if err = db.DBO.ExecuteMultiBatch(); err != nil { return "", err } return newestFBlock.GetKeyMR().String(), nil }
go
func (db *TXDatabaseOverlay) update() (string, error) { newestFBlock, err := fblockHead() if err != nil { return "", err } start, err := db.FetchNextFBlockHeight() if err != nil { return "", err } // Make sure we didn't switch networks genesis, err := db.DBO.FetchFBlockByHeight(0) if err != nil { return "", err } if genesis != nil { genesis2, err := getdblockbyheight(0) if err != nil { return "", err } var gensisFBlockKeyMr interfaces.IHash for _, e := range genesis2.GetDBEntries() { if e.GetChainID().String() == "000000000000000000000000000000000000000000000000000000000000000f" { gensisFBlockKeyMr = e.GetKeyMR() break } } if gensisFBlockKeyMr == nil { return "", fmt.Errorf("unable to fetch the genesis block via the api") } if !gensisFBlockKeyMr.IsSameAs(genesis.GetKeyMR()) { start = 0 } } newestHeight := newestFBlock.GetDatabaseHeight() // If the newest block in the tx cashe has a greater height than the newest // fblock then clear the cashe and start from 0. if start >= newestHeight { return newestFBlock.GetKeyMR().String(), nil } db.DBO.StartMultiBatch() for i := start; i <= newestHeight; i++ { if i%1000 == 0 { if newestHeight-start > 1000 { fmt.Printf("Fetching block %v/%v\n", i, newestHeight) } } fblock, err := getfblockbyheight(i) if err != nil { db.DBO.ExecuteMultiBatch() return "", err } db.DBO.ProcessFBlockMultiBatch(fblock) // Save to DB every 500 blocks if i%500 == 0 { db.DBO.ExecuteMultiBatch() db.DBO.StartMultiBatch() } // If the wallet is stopped, this process becomes hard to kill. Have it exit if db.quit { break } } if !db.quit { fmt.Printf("Fetching block %v/%v\n", newestHeight, newestHeight) } // Save the remaining blocks if err = db.DBO.ExecuteMultiBatch(); err != nil { return "", err } return newestFBlock.GetKeyMR().String(), nil }
[ "func", "(", "db", "*", "TXDatabaseOverlay", ")", "update", "(", ")", "(", "string", ",", "error", ")", "{", "newestFBlock", ",", "err", ":=", "fblockHead", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "start", ",", "err", ":=", "db", ".", "FetchNextFBlockHeight", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Make sure we didn't switch networks", "genesis", ",", "err", ":=", "db", ".", "DBO", ".", "FetchFBlockByHeight", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "genesis", "!=", "nil", "{", "genesis2", ",", "err", ":=", "getdblockbyheight", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "var", "gensisFBlockKeyMr", "interfaces", ".", "IHash", "\n", "for", "_", ",", "e", ":=", "range", "genesis2", ".", "GetDBEntries", "(", ")", "{", "if", "e", ".", "GetChainID", "(", ")", ".", "String", "(", ")", "==", "\"", "\"", "{", "gensisFBlockKeyMr", "=", "e", ".", "GetKeyMR", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "gensisFBlockKeyMr", "==", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "gensisFBlockKeyMr", ".", "IsSameAs", "(", "genesis", ".", "GetKeyMR", "(", ")", ")", "{", "start", "=", "0", "\n", "}", "\n", "}", "\n\n", "newestHeight", ":=", "newestFBlock", ".", "GetDatabaseHeight", "(", ")", "\n\n", "// If the newest block in the tx cashe has a greater height than the newest", "// fblock then clear the cashe and start from 0.", "if", "start", ">=", "newestHeight", "{", "return", "newestFBlock", ".", "GetKeyMR", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "}", "\n\n", "db", ".", "DBO", ".", "StartMultiBatch", "(", ")", "\n", "for", "i", ":=", "start", ";", "i", "<=", "newestHeight", ";", "i", "++", "{", "if", "i", "%", "1000", "==", "0", "{", "if", "newestHeight", "-", "start", ">", "1000", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "i", ",", "newestHeight", ")", "\n", "}", "\n", "}", "\n", "fblock", ",", "err", ":=", "getfblockbyheight", "(", "i", ")", "\n", "if", "err", "!=", "nil", "{", "db", ".", "DBO", ".", "ExecuteMultiBatch", "(", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "db", ".", "DBO", ".", "ProcessFBlockMultiBatch", "(", "fblock", ")", "\n\n", "// Save to DB every 500 blocks", "if", "i", "%", "500", "==", "0", "{", "db", ".", "DBO", ".", "ExecuteMultiBatch", "(", ")", "\n", "db", ".", "DBO", ".", "StartMultiBatch", "(", ")", "\n", "}", "\n\n", "// If the wallet is stopped, this process becomes hard to kill. Have it exit", "if", "db", ".", "quit", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "db", ".", "quit", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "newestHeight", ",", "newestHeight", ")", "\n", "}", "\n\n", "// Save the remaining blocks", "if", "err", "=", "db", ".", "DBO", ".", "ExecuteMultiBatch", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "newestFBlock", ".", "GetKeyMR", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// update gets all fblocks written since the database was last updated, and // returns the most recent fblock keymr.
[ "update", "gets", "all", "fblocks", "written", "since", "the", "database", "was", "last", "updated", "and", "returns", "the", "most", "recent", "fblock", "keymr", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/txdatabase.go#L290-L373
15,263
FactomProject/factom
wallet/txdatabase.go
fblockHead
func fblockHead() (interfaces.IFBlock, error) { fblockID := "000000000000000000000000000000000000000000000000000000000000000f" dbhead, err := factom.GetDBlockHead() if err != nil { return nil, err } dblock, err := factom.GetDBlock(dbhead) if err != nil { return nil, err } var fblockmr string for _, eblock := range dblock.EntryBlockList { if eblock.ChainID == fblockID { fblockmr = eblock.KeyMR } } if fblockmr == "" { return nil, err } return getfblock(fblockmr) }
go
func fblockHead() (interfaces.IFBlock, error) { fblockID := "000000000000000000000000000000000000000000000000000000000000000f" dbhead, err := factom.GetDBlockHead() if err != nil { return nil, err } dblock, err := factom.GetDBlock(dbhead) if err != nil { return nil, err } var fblockmr string for _, eblock := range dblock.EntryBlockList { if eblock.ChainID == fblockID { fblockmr = eblock.KeyMR } } if fblockmr == "" { return nil, err } return getfblock(fblockmr) }
[ "func", "fblockHead", "(", ")", "(", "interfaces", ".", "IFBlock", ",", "error", ")", "{", "fblockID", ":=", "\"", "\"", "\n\n", "dbhead", ",", "err", ":=", "factom", ".", "GetDBlockHead", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dblock", ",", "err", ":=", "factom", ".", "GetDBlock", "(", "dbhead", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "fblockmr", "string", "\n", "for", "_", ",", "eblock", ":=", "range", "dblock", ".", "EntryBlockList", "{", "if", "eblock", ".", "ChainID", "==", "fblockID", "{", "fblockmr", "=", "eblock", ".", "KeyMR", "\n", "}", "\n", "}", "\n", "if", "fblockmr", "==", "\"", "\"", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "getfblock", "(", "fblockmr", ")", "\n", "}" ]
// fblockHead gets the most recent fblock.
[ "fblockHead", "gets", "the", "most", "recent", "fblock", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/txdatabase.go#L376-L399
15,264
FactomProject/factom
transaction.go
String
func (tx *Transaction) String() (s string) { if tx.Name != "" { s += fmt.Sprintln("Name:", tx.Name) } if tx.IsSigned { s += fmt.Sprintln("TxID:", tx.TxID) } s += fmt.Sprintln("Timestamp:", tx.Timestamp) if tx.BlockHeight != 0 { s += fmt.Sprintln("BlockHeight:", tx.BlockHeight) } s += fmt.Sprintln("TotalInputs:", FactoshiToFactoid(tx.TotalInputs)) s += fmt.Sprintln("TotalOutputs:", FactoshiToFactoid(tx.TotalOutputs)) s += fmt.Sprintln("TotalECOutputs:", FactoshiToFactoid(tx.TotalECOutputs)) for _, in := range tx.Inputs { s += fmt.Sprintln( "Input:", in.Address, FactoshiToFactoid(in.Amount), ) } for _, out := range tx.Outputs { s += fmt.Sprintln( "Output:", out.Address, FactoshiToFactoid(out.Amount), ) } for _, ec := range tx.ECOutputs { s += fmt.Sprintln( "ECOutput:", ec.Address, FactoshiToFactoid(ec.Amount), ) } s += fmt.Sprintln("FeesPaid:", FactoshiToFactoid(tx.FeesPaid)) if tx.FeesRequired != 0 { s += fmt.Sprintln("FeesRequired:", FactoshiToFactoid(tx.FeesRequired)) } s += fmt.Sprintln("Signed:", tx.IsSigned) return s }
go
func (tx *Transaction) String() (s string) { if tx.Name != "" { s += fmt.Sprintln("Name:", tx.Name) } if tx.IsSigned { s += fmt.Sprintln("TxID:", tx.TxID) } s += fmt.Sprintln("Timestamp:", tx.Timestamp) if tx.BlockHeight != 0 { s += fmt.Sprintln("BlockHeight:", tx.BlockHeight) } s += fmt.Sprintln("TotalInputs:", FactoshiToFactoid(tx.TotalInputs)) s += fmt.Sprintln("TotalOutputs:", FactoshiToFactoid(tx.TotalOutputs)) s += fmt.Sprintln("TotalECOutputs:", FactoshiToFactoid(tx.TotalECOutputs)) for _, in := range tx.Inputs { s += fmt.Sprintln( "Input:", in.Address, FactoshiToFactoid(in.Amount), ) } for _, out := range tx.Outputs { s += fmt.Sprintln( "Output:", out.Address, FactoshiToFactoid(out.Amount), ) } for _, ec := range tx.ECOutputs { s += fmt.Sprintln( "ECOutput:", ec.Address, FactoshiToFactoid(ec.Amount), ) } s += fmt.Sprintln("FeesPaid:", FactoshiToFactoid(tx.FeesPaid)) if tx.FeesRequired != 0 { s += fmt.Sprintln("FeesRequired:", FactoshiToFactoid(tx.FeesRequired)) } s += fmt.Sprintln("Signed:", tx.IsSigned) return s }
[ "func", "(", "tx", "*", "Transaction", ")", "String", "(", ")", "(", "s", "string", ")", "{", "if", "tx", ".", "Name", "!=", "\"", "\"", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "tx", ".", "Name", ")", "\n", "}", "\n", "if", "tx", ".", "IsSigned", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "tx", ".", "TxID", ")", "\n", "}", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "tx", ".", "Timestamp", ")", "\n", "if", "tx", ".", "BlockHeight", "!=", "0", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "tx", ".", "BlockHeight", ")", "\n", "}", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "FactoshiToFactoid", "(", "tx", ".", "TotalInputs", ")", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "FactoshiToFactoid", "(", "tx", ".", "TotalOutputs", ")", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "FactoshiToFactoid", "(", "tx", ".", "TotalECOutputs", ")", ")", "\n", "for", "_", ",", "in", ":=", "range", "tx", ".", "Inputs", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "in", ".", "Address", ",", "FactoshiToFactoid", "(", "in", ".", "Amount", ")", ",", ")", "\n", "}", "\n", "for", "_", ",", "out", ":=", "range", "tx", ".", "Outputs", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "out", ".", "Address", ",", "FactoshiToFactoid", "(", "out", ".", "Amount", ")", ",", ")", "\n", "}", "\n", "for", "_", ",", "ec", ":=", "range", "tx", ".", "ECOutputs", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "ec", ".", "Address", ",", "FactoshiToFactoid", "(", "ec", ".", "Amount", ")", ",", ")", "\n", "}", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "FactoshiToFactoid", "(", "tx", ".", "FeesPaid", ")", ")", "\n", "if", "tx", ".", "FeesRequired", "!=", "0", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "FactoshiToFactoid", "(", "tx", ".", "FeesRequired", ")", ")", "\n", "}", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "tx", ".", "IsSigned", ")", "\n\n", "return", "s", "\n", "}" ]
// String prints the formatted data of a transaction.
[ "String", "prints", "the", "formatted", "data", "of", "a", "transaction", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/transaction.go#L37-L79
15,265
FactomProject/factom
transaction.go
MarshalJSON
func (tx *Transaction) MarshalJSON() ([]byte, error) { tmp := &struct { BlockHeight uint32 `json:"blockheight,omitempty"` FeesPaid uint64 `json:"feespaid,omitempty"` FeesRequired uint64 `json:"feesrequired,omitempty"` IsSigned bool `json:"signed"` Name string `json:"name,omitempty"` Timestamp int64 `json:"timestamp"` TotalECOutputs uint64 `json:"totalecoutputs"` TotalInputs uint64 `json:"totalinputs"` TotalOutputs uint64 `json:"totaloutputs"` Inputs []*TransAddress `json:"inputs"` Outputs []*TransAddress `json:"outputs"` ECOutputs []*TransAddress `json:"ecoutputs"` TxID string `json:"txid,omitempty"` }{ BlockHeight: tx.BlockHeight, FeesPaid: tx.FeesPaid, FeesRequired: tx.FeesRequired, IsSigned: tx.IsSigned, Name: tx.Name, Timestamp: tx.Timestamp.Unix(), TotalECOutputs: tx.TotalECOutputs, TotalInputs: tx.TotalInputs, TotalOutputs: tx.TotalOutputs, Inputs: tx.Inputs, Outputs: tx.Outputs, ECOutputs: tx.ECOutputs, TxID: tx.TxID, } return json.Marshal(tmp) }
go
func (tx *Transaction) MarshalJSON() ([]byte, error) { tmp := &struct { BlockHeight uint32 `json:"blockheight,omitempty"` FeesPaid uint64 `json:"feespaid,omitempty"` FeesRequired uint64 `json:"feesrequired,omitempty"` IsSigned bool `json:"signed"` Name string `json:"name,omitempty"` Timestamp int64 `json:"timestamp"` TotalECOutputs uint64 `json:"totalecoutputs"` TotalInputs uint64 `json:"totalinputs"` TotalOutputs uint64 `json:"totaloutputs"` Inputs []*TransAddress `json:"inputs"` Outputs []*TransAddress `json:"outputs"` ECOutputs []*TransAddress `json:"ecoutputs"` TxID string `json:"txid,omitempty"` }{ BlockHeight: tx.BlockHeight, FeesPaid: tx.FeesPaid, FeesRequired: tx.FeesRequired, IsSigned: tx.IsSigned, Name: tx.Name, Timestamp: tx.Timestamp.Unix(), TotalECOutputs: tx.TotalECOutputs, TotalInputs: tx.TotalInputs, TotalOutputs: tx.TotalOutputs, Inputs: tx.Inputs, Outputs: tx.Outputs, ECOutputs: tx.ECOutputs, TxID: tx.TxID, } return json.Marshal(tmp) }
[ "func", "(", "tx", "*", "Transaction", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "tmp", ":=", "&", "struct", "{", "BlockHeight", "uint32", "`json:\"blockheight,omitempty\"`", "\n", "FeesPaid", "uint64", "`json:\"feespaid,omitempty\"`", "\n", "FeesRequired", "uint64", "`json:\"feesrequired,omitempty\"`", "\n", "IsSigned", "bool", "`json:\"signed\"`", "\n", "Name", "string", "`json:\"name,omitempty\"`", "\n", "Timestamp", "int64", "`json:\"timestamp\"`", "\n", "TotalECOutputs", "uint64", "`json:\"totalecoutputs\"`", "\n", "TotalInputs", "uint64", "`json:\"totalinputs\"`", "\n", "TotalOutputs", "uint64", "`json:\"totaloutputs\"`", "\n", "Inputs", "[", "]", "*", "TransAddress", "`json:\"inputs\"`", "\n", "Outputs", "[", "]", "*", "TransAddress", "`json:\"outputs\"`", "\n", "ECOutputs", "[", "]", "*", "TransAddress", "`json:\"ecoutputs\"`", "\n", "TxID", "string", "`json:\"txid,omitempty\"`", "\n", "}", "{", "BlockHeight", ":", "tx", ".", "BlockHeight", ",", "FeesPaid", ":", "tx", ".", "FeesPaid", ",", "FeesRequired", ":", "tx", ".", "FeesRequired", ",", "IsSigned", ":", "tx", ".", "IsSigned", ",", "Name", ":", "tx", ".", "Name", ",", "Timestamp", ":", "tx", ".", "Timestamp", ".", "Unix", "(", ")", ",", "TotalECOutputs", ":", "tx", ".", "TotalECOutputs", ",", "TotalInputs", ":", "tx", ".", "TotalInputs", ",", "TotalOutputs", ":", "tx", ".", "TotalOutputs", ",", "Inputs", ":", "tx", ".", "Inputs", ",", "Outputs", ":", "tx", ".", "Outputs", ",", "ECOutputs", ":", "tx", ".", "ECOutputs", ",", "TxID", ":", "tx", ".", "TxID", ",", "}", "\n\n", "return", "json", ".", "Marshal", "(", "tmp", ")", "\n", "}" ]
// MarshalJSON converts the Transaction into a JSON object
[ "MarshalJSON", "converts", "the", "Transaction", "into", "a", "JSON", "object" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/transaction.go#L82-L114
15,266
FactomProject/factom
transaction.go
UnmarshalJSON
func (tx *Transaction) UnmarshalJSON(data []byte) error { type jsontx struct { BlockHeight uint32 `json:"blockheight,omitempty"` FeesPaid uint64 `json:"feespaid,omitempty"` FeesRequired uint64 `json:"feesrequired,omitempty"` IsSigned bool `json:"signed"` Name string `json:"name,omitempty"` Timestamp int64 `json:"timestamp"` TotalECOutputs uint64 `json:"totalecoutputs"` TotalInputs uint64 `json:"totalinputs"` TotalOutputs uint64 `json:"totaloutputs"` Inputs []*TransAddress `json:"inputs"` Outputs []*TransAddress `json:"outputs"` ECOutputs []*TransAddress `json:"ecoutputs"` TxID string `json:"txid,omitempty"` } tmp := new(jsontx) if err := json.Unmarshal(data, tmp); err != nil { return err } tx.BlockHeight = tmp.BlockHeight tx.FeesPaid = tmp.FeesPaid tx.FeesRequired = tmp.FeesRequired tx.IsSigned = tmp.IsSigned tx.Name = tmp.Name tx.Timestamp = time.Unix(tmp.Timestamp, 0) tx.TotalECOutputs = tmp.TotalECOutputs tx.TotalInputs = tmp.TotalInputs tx.TotalOutputs = tmp.TotalOutputs tx.Inputs = tmp.Inputs tx.Outputs = tmp.Outputs tx.ECOutputs = tmp.ECOutputs tx.TxID = tmp.TxID return nil }
go
func (tx *Transaction) UnmarshalJSON(data []byte) error { type jsontx struct { BlockHeight uint32 `json:"blockheight,omitempty"` FeesPaid uint64 `json:"feespaid,omitempty"` FeesRequired uint64 `json:"feesrequired,omitempty"` IsSigned bool `json:"signed"` Name string `json:"name,omitempty"` Timestamp int64 `json:"timestamp"` TotalECOutputs uint64 `json:"totalecoutputs"` TotalInputs uint64 `json:"totalinputs"` TotalOutputs uint64 `json:"totaloutputs"` Inputs []*TransAddress `json:"inputs"` Outputs []*TransAddress `json:"outputs"` ECOutputs []*TransAddress `json:"ecoutputs"` TxID string `json:"txid,omitempty"` } tmp := new(jsontx) if err := json.Unmarshal(data, tmp); err != nil { return err } tx.BlockHeight = tmp.BlockHeight tx.FeesPaid = tmp.FeesPaid tx.FeesRequired = tmp.FeesRequired tx.IsSigned = tmp.IsSigned tx.Name = tmp.Name tx.Timestamp = time.Unix(tmp.Timestamp, 0) tx.TotalECOutputs = tmp.TotalECOutputs tx.TotalInputs = tmp.TotalInputs tx.TotalOutputs = tmp.TotalOutputs tx.Inputs = tmp.Inputs tx.Outputs = tmp.Outputs tx.ECOutputs = tmp.ECOutputs tx.TxID = tmp.TxID return nil }
[ "func", "(", "tx", "*", "Transaction", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "type", "jsontx", "struct", "{", "BlockHeight", "uint32", "`json:\"blockheight,omitempty\"`", "\n", "FeesPaid", "uint64", "`json:\"feespaid,omitempty\"`", "\n", "FeesRequired", "uint64", "`json:\"feesrequired,omitempty\"`", "\n", "IsSigned", "bool", "`json:\"signed\"`", "\n", "Name", "string", "`json:\"name,omitempty\"`", "\n", "Timestamp", "int64", "`json:\"timestamp\"`", "\n", "TotalECOutputs", "uint64", "`json:\"totalecoutputs\"`", "\n", "TotalInputs", "uint64", "`json:\"totalinputs\"`", "\n", "TotalOutputs", "uint64", "`json:\"totaloutputs\"`", "\n", "Inputs", "[", "]", "*", "TransAddress", "`json:\"inputs\"`", "\n", "Outputs", "[", "]", "*", "TransAddress", "`json:\"outputs\"`", "\n", "ECOutputs", "[", "]", "*", "TransAddress", "`json:\"ecoutputs\"`", "\n", "TxID", "string", "`json:\"txid,omitempty\"`", "\n", "}", "\n", "tmp", ":=", "new", "(", "jsontx", ")", "\n\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "tmp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "tx", ".", "BlockHeight", "=", "tmp", ".", "BlockHeight", "\n", "tx", ".", "FeesPaid", "=", "tmp", ".", "FeesPaid", "\n", "tx", ".", "FeesRequired", "=", "tmp", ".", "FeesRequired", "\n", "tx", ".", "IsSigned", "=", "tmp", ".", "IsSigned", "\n", "tx", ".", "Name", "=", "tmp", ".", "Name", "\n", "tx", ".", "Timestamp", "=", "time", ".", "Unix", "(", "tmp", ".", "Timestamp", ",", "0", ")", "\n", "tx", ".", "TotalECOutputs", "=", "tmp", ".", "TotalECOutputs", "\n", "tx", ".", "TotalInputs", "=", "tmp", ".", "TotalInputs", "\n", "tx", ".", "TotalOutputs", "=", "tmp", ".", "TotalOutputs", "\n", "tx", ".", "Inputs", "=", "tmp", ".", "Inputs", "\n", "tx", ".", "Outputs", "=", "tmp", ".", "Outputs", "\n", "tx", ".", "ECOutputs", "=", "tmp", ".", "ECOutputs", "\n", "tx", ".", "TxID", "=", "tmp", ".", "TxID", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON converts the JSON Transaction back into a Transaction
[ "UnmarshalJSON", "converts", "the", "JSON", "Transaction", "back", "into", "a", "Transaction" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/transaction.go#L117-L154
15,267
FactomProject/factom
transaction.go
NewTransaction
func NewTransaction(name string) (*Transaction, error) { params := transactionRequest{Name: name} req := NewJSON2Request("new-transaction", APICounter(), params) resp, err := walletRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } tx := new(Transaction) if err := json.Unmarshal(resp.JSONResult(), tx); err != nil { return nil, err } return tx, nil }
go
func NewTransaction(name string) (*Transaction, error) { params := transactionRequest{Name: name} req := NewJSON2Request("new-transaction", APICounter(), params) resp, err := walletRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } tx := new(Transaction) if err := json.Unmarshal(resp.JSONResult(), tx); err != nil { return nil, err } return tx, nil }
[ "func", "NewTransaction", "(", "name", "string", ")", "(", "*", "Transaction", ",", "error", ")", "{", "params", ":=", "transactionRequest", "{", "Name", ":", "name", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n\n", "resp", ",", "err", ":=", "walletRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "resp", ".", "Error", "\n", "}", "\n\n", "tx", ":=", "new", "(", "Transaction", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "tx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "tx", ",", "nil", "\n", "}" ]
// NewTransaction creates a new temporary Transaction in the wallet
[ "NewTransaction", "creates", "a", "new", "temporary", "Transaction", "in", "the", "wallet" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/transaction.go#L157-L174
15,268
FactomProject/factom
transaction.go
GetTmpTransaction
func GetTmpTransaction(name string) (*Transaction, error) { txs, err := ListTransactionsTmp() if err != nil { return nil, err } for _, tx := range txs { if tx.Name == name { return tx, nil } } return nil, fmt.Errorf("Transaction not found") }
go
func GetTmpTransaction(name string) (*Transaction, error) { txs, err := ListTransactionsTmp() if err != nil { return nil, err } for _, tx := range txs { if tx.Name == name { return tx, nil } } return nil, fmt.Errorf("Transaction not found") }
[ "func", "GetTmpTransaction", "(", "name", "string", ")", "(", "*", "Transaction", ",", "error", ")", "{", "txs", ",", "err", ":=", "ListTransactionsTmp", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "tx", ":=", "range", "txs", "{", "if", "tx", ".", "Name", "==", "name", "{", "return", "tx", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// GetTmpTransaction gets a temporary transaction from the wallet
[ "GetTmpTransaction", "gets", "a", "temporary", "transaction", "from", "the", "wallet" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/transaction.go#L667-L680
15,269
FactomProject/factom
wallet/importexportldb.go
ImportLDBWalletFromMnemonic
func ImportLDBWalletFromMnemonic(mnemonic, path string) (*Wallet, error) { mnemonic, err := factom.ParseAndValidateMnemonic(mnemonic) if err != nil { return nil, err } // check if the file exists _, err = os.Stat(path) if err == nil { return nil, fmt.Errorf("%s: file already exists", path) } db, err := NewLevelDB(path) if err != nil { return nil, err } seed := new(DBSeed) seed.MnemonicSeed = mnemonic if err := db.InsertDBSeed(seed); err != nil { return nil, err } w := new(Wallet) w.transactions = make(map[string]*factoid.Transaction) w.WalletDatabaseOverlay = db return w, nil }
go
func ImportLDBWalletFromMnemonic(mnemonic, path string) (*Wallet, error) { mnemonic, err := factom.ParseAndValidateMnemonic(mnemonic) if err != nil { return nil, err } // check if the file exists _, err = os.Stat(path) if err == nil { return nil, fmt.Errorf("%s: file already exists", path) } db, err := NewLevelDB(path) if err != nil { return nil, err } seed := new(DBSeed) seed.MnemonicSeed = mnemonic if err := db.InsertDBSeed(seed); err != nil { return nil, err } w := new(Wallet) w.transactions = make(map[string]*factoid.Transaction) w.WalletDatabaseOverlay = db return w, nil }
[ "func", "ImportLDBWalletFromMnemonic", "(", "mnemonic", ",", "path", "string", ")", "(", "*", "Wallet", ",", "error", ")", "{", "mnemonic", ",", "err", ":=", "factom", ".", "ParseAndValidateMnemonic", "(", "mnemonic", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// check if the file exists", "_", ",", "err", "=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n\n", "db", ",", "err", ":=", "NewLevelDB", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "seed", ":=", "new", "(", "DBSeed", ")", "\n", "seed", ".", "MnemonicSeed", "=", "mnemonic", "\n", "if", "err", ":=", "db", ".", "InsertDBSeed", "(", "seed", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "w", ":=", "new", "(", "Wallet", ")", "\n", "w", ".", "transactions", "=", "make", "(", "map", "[", "string", "]", "*", "factoid", ".", "Transaction", ")", "\n", "w", ".", "WalletDatabaseOverlay", "=", "db", "\n\n", "return", "w", ",", "nil", "\n", "}" ]
// ImportWalletFromMnemonic creates a new wallet with a provided Mnemonic seed // defined in bip-0039.
[ "ImportWalletFromMnemonic", "creates", "a", "new", "wallet", "with", "a", "provided", "Mnemonic", "seed", "defined", "in", "bip", "-", "0039", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/importexportldb.go#L17-L45
15,270
FactomProject/factom
wallet/database.go
Close
func (w *Wallet) Close() error { if w.WalletDatabaseOverlay == nil { return nil } return w.DBO.Close() }
go
func (w *Wallet) Close() error { if w.WalletDatabaseOverlay == nil { return nil } return w.DBO.Close() }
[ "func", "(", "w", "*", "Wallet", ")", "Close", "(", ")", "error", "{", "if", "w", ".", "WalletDatabaseOverlay", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "w", ".", "DBO", ".", "Close", "(", ")", "\n", "}" ]
// Close closes a Factom Wallet Database
[ "Close", "closes", "a", "Factom", "Wallet", "Database" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/database.go#L104-L109
15,271
FactomProject/factom
wallet/database.go
GetAllAddresses
func (w *Wallet) GetAllAddresses() ([]*factom.FactoidAddress, []*factom.ECAddress, error) { fcs, err := w.GetAllFCTAddresses() if err != nil { return nil, nil, err } ecs, err := w.GetAllECAddresses() if err != nil { return nil, nil, err } return fcs, ecs, nil }
go
func (w *Wallet) GetAllAddresses() ([]*factom.FactoidAddress, []*factom.ECAddress, error) { fcs, err := w.GetAllFCTAddresses() if err != nil { return nil, nil, err } ecs, err := w.GetAllECAddresses() if err != nil { return nil, nil, err } return fcs, ecs, nil }
[ "func", "(", "w", "*", "Wallet", ")", "GetAllAddresses", "(", ")", "(", "[", "]", "*", "factom", ".", "FactoidAddress", ",", "[", "]", "*", "factom", ".", "ECAddress", ",", "error", ")", "{", "fcs", ",", "err", ":=", "w", ".", "GetAllFCTAddresses", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "ecs", ",", "err", ":=", "w", ".", "GetAllECAddresses", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "fcs", ",", "ecs", ",", "nil", "\n", "}" ]
// GetAllAddresses retrieves all Entry Credit and Factoid Addresses from the // Wallet Database.
[ "GetAllAddresses", "retrieves", "all", "Entry", "Credit", "and", "Factoid", "Addresses", "from", "the", "Wallet", "Database", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/database.go#L139-L150
15,272
FactomProject/factom
wallet/database.go
GetSeed
func (w *Wallet) GetSeed() (string, error) { seed, err := w.GetDBSeed() if err != nil { return "", err } return seed.MnemonicSeed, nil }
go
func (w *Wallet) GetSeed() (string, error) { seed, err := w.GetDBSeed() if err != nil { return "", err } return seed.MnemonicSeed, nil }
[ "func", "(", "w", "*", "Wallet", ")", "GetSeed", "(", ")", "(", "string", ",", "error", ")", "{", "seed", ",", "err", ":=", "w", ".", "GetDBSeed", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "seed", ".", "MnemonicSeed", ",", "nil", "\n", "}" ]
// GetSeed returns the string representaion of the Wallet Seed. The Wallet Seed // can be used to regenerate the Factoid and Entry Credit Addresses previously // generated by the wallet. Note that Addresses that are imported into the // Wallet cannot be regenerated using the Wallet Seed.
[ "GetSeed", "returns", "the", "string", "representaion", "of", "the", "Wallet", "Seed", ".", "The", "Wallet", "Seed", "can", "be", "used", "to", "regenerate", "the", "Factoid", "and", "Entry", "Credit", "Addresses", "previously", "generated", "by", "the", "wallet", ".", "Note", "that", "Addresses", "that", "are", "imported", "into", "the", "Wallet", "cannot", "be", "regenerated", "using", "the", "Wallet", "Seed", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/database.go#L156-L163
15,273
FactomProject/factom
wallet/util.go
SeedString
func SeedString(seed []byte) string { if len(seed) != SeedLength { return "" } buf := new(bytes.Buffer) // 2 byte Seed Address Prefix buf.Write(seedPrefix) // 64 byte Seed buf.Write(seed) // 4 byte Checksum check := shad(buf.Bytes())[:4] buf.Write(check) return base58.Encode(buf.Bytes()) }
go
func SeedString(seed []byte) string { if len(seed) != SeedLength { return "" } buf := new(bytes.Buffer) // 2 byte Seed Address Prefix buf.Write(seedPrefix) // 64 byte Seed buf.Write(seed) // 4 byte Checksum check := shad(buf.Bytes())[:4] buf.Write(check) return base58.Encode(buf.Bytes()) }
[ "func", "SeedString", "(", "seed", "[", "]", "byte", ")", "string", "{", "if", "len", "(", "seed", ")", "!=", "SeedLength", "{", "return", "\"", "\"", "\n", "}", "\n\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "// 2 byte Seed Address Prefix", "buf", ".", "Write", "(", "seedPrefix", ")", "\n\n", "// 64 byte Seed", "buf", ".", "Write", "(", "seed", ")", "\n\n", "// 4 byte Checksum", "check", ":=", "shad", "(", "buf", ".", "Bytes", "(", ")", ")", "[", ":", "4", "]", "\n", "buf", ".", "Write", "(", "check", ")", "\n\n", "return", "base58", ".", "Encode", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// SeedString returnes the string representation of a raw Wallet Seed or Next // Wallet Seed.
[ "SeedString", "returnes", "the", "string", "representation", "of", "a", "raw", "Wallet", "Seed", "or", "Next", "Wallet", "Seed", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/util.go#L35-L53
15,274
FactomProject/factom
entry.go
ComposeEntryCommit
func ComposeEntryCommit(e *Entry, ec *ECAddress) (*JSON2Request, error) { buf := new(bytes.Buffer) // 1 byte version buf.Write([]byte{0}) // 6 byte milliTimestamp (truncated unix time) buf.Write(milliTime()) // 32 byte Entry Hash buf.Write(e.Hash()) // 1 byte number of entry credits to pay if c, err := EntryCost(e); err != nil { return nil, err } else { buf.WriteByte(byte(c)) } // 32 byte Entry Credit Address Public Key + 64 byte Signature sig := ec.Sign(buf.Bytes()) buf.Write(ec.PubBytes()) buf.Write(sig[:]) params := messageRequest{Message: hex.EncodeToString(buf.Bytes())} req := NewJSON2Request("commit-entry", APICounter(), params) return req, nil }
go
func ComposeEntryCommit(e *Entry, ec *ECAddress) (*JSON2Request, error) { buf := new(bytes.Buffer) // 1 byte version buf.Write([]byte{0}) // 6 byte milliTimestamp (truncated unix time) buf.Write(milliTime()) // 32 byte Entry Hash buf.Write(e.Hash()) // 1 byte number of entry credits to pay if c, err := EntryCost(e); err != nil { return nil, err } else { buf.WriteByte(byte(c)) } // 32 byte Entry Credit Address Public Key + 64 byte Signature sig := ec.Sign(buf.Bytes()) buf.Write(ec.PubBytes()) buf.Write(sig[:]) params := messageRequest{Message: hex.EncodeToString(buf.Bytes())} req := NewJSON2Request("commit-entry", APICounter(), params) return req, nil }
[ "func", "ComposeEntryCommit", "(", "e", "*", "Entry", ",", "ec", "*", "ECAddress", ")", "(", "*", "JSON2Request", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "// 1 byte version", "buf", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n\n", "// 6 byte milliTimestamp (truncated unix time)", "buf", ".", "Write", "(", "milliTime", "(", ")", ")", "\n\n", "// 32 byte Entry Hash", "buf", ".", "Write", "(", "e", ".", "Hash", "(", ")", ")", "\n\n", "// 1 byte number of entry credits to pay", "if", "c", ",", "err", ":=", "EntryCost", "(", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "buf", ".", "WriteByte", "(", "byte", "(", "c", ")", ")", "\n", "}", "\n\n", "// 32 byte Entry Credit Address Public Key + 64 byte Signature", "sig", ":=", "ec", ".", "Sign", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "buf", ".", "Write", "(", "ec", ".", "PubBytes", "(", ")", ")", "\n", "buf", ".", "Write", "(", "sig", "[", ":", "]", ")", "\n\n", "params", ":=", "messageRequest", "{", "Message", ":", "hex", ".", "EncodeToString", "(", "buf", ".", "Bytes", "(", ")", ")", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// ComposeEntryCommit creates a JSON2Request to commit a new Entry via the // factomd web api. The request includes the marshaled MessageRequest with the // Entry Credit Signature.
[ "ComposeEntryCommit", "creates", "a", "JSON2Request", "to", "commit", "a", "new", "Entry", "via", "the", "factomd", "web", "api", ".", "The", "request", "includes", "the", "marshaled", "MessageRequest", "with", "the", "Entry", "Credit", "Signature", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/entry.go#L157-L185
15,275
FactomProject/factom
entry.go
ComposeEntryReveal
func ComposeEntryReveal(e *Entry) (*JSON2Request, error) { p, err := e.MarshalBinary() if err != nil { return nil, err } params := entryRequest{Entry: hex.EncodeToString(p)} req := NewJSON2Request("reveal-entry", APICounter(), params) return req, nil }
go
func ComposeEntryReveal(e *Entry) (*JSON2Request, error) { p, err := e.MarshalBinary() if err != nil { return nil, err } params := entryRequest{Entry: hex.EncodeToString(p)} req := NewJSON2Request("reveal-entry", APICounter(), params) return req, nil }
[ "func", "ComposeEntryReveal", "(", "e", "*", "Entry", ")", "(", "*", "JSON2Request", ",", "error", ")", "{", "p", ",", "err", ":=", "e", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "params", ":=", "entryRequest", "{", "Entry", ":", "hex", ".", "EncodeToString", "(", "p", ")", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// ComposeEntryReveal creates a JSON2Request to reveal the Entry via the factomd // web api.
[ "ComposeEntryReveal", "creates", "a", "JSON2Request", "to", "reveal", "the", "Entry", "via", "the", "factomd", "web", "api", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/entry.go#L189-L199
15,276
FactomProject/factom
entry.go
CommitEntry
func CommitEntry(e *Entry, ec *ECAddress) (string, error) { type commitResponse struct { Message string `json:"message"` TxID string `json:"txid"` } req, err := ComposeEntryCommit(e, ec) if err != nil { return "", err } resp, err := factomdRequest(req) if err != nil { return "", err } if resp.Error != nil { return "", resp.Error } r := new(commitResponse) if err := json.Unmarshal(resp.JSONResult(), r); err != nil { return "", err } return r.TxID, nil }
go
func CommitEntry(e *Entry, ec *ECAddress) (string, error) { type commitResponse struct { Message string `json:"message"` TxID string `json:"txid"` } req, err := ComposeEntryCommit(e, ec) if err != nil { return "", err } resp, err := factomdRequest(req) if err != nil { return "", err } if resp.Error != nil { return "", resp.Error } r := new(commitResponse) if err := json.Unmarshal(resp.JSONResult(), r); err != nil { return "", err } return r.TxID, nil }
[ "func", "CommitEntry", "(", "e", "*", "Entry", ",", "ec", "*", "ECAddress", ")", "(", "string", ",", "error", ")", "{", "type", "commitResponse", "struct", "{", "Message", "string", "`json:\"message\"`", "\n", "TxID", "string", "`json:\"txid\"`", "\n", "}", "\n\n", "req", ",", "err", ":=", "ComposeEntryCommit", "(", "e", ",", "ec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "factomdRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "\"", "\"", ",", "resp", ".", "Error", "\n", "}", "\n", "r", ":=", "new", "(", "commitResponse", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "r", ".", "TxID", ",", "nil", "\n", "}" ]
// CommitEntry sends the signed Entry Hash and the Entry Credit public key to // the factom network. Once the payment is verified and the network is commited // to publishing the Entry it may be published with a call to RevealEntry.
[ "CommitEntry", "sends", "the", "signed", "Entry", "Hash", "and", "the", "Entry", "Credit", "public", "key", "to", "the", "factom", "network", ".", "Once", "the", "payment", "is", "verified", "and", "the", "network", "is", "commited", "to", "publishing", "the", "Entry", "it", "may", "be", "published", "with", "a", "call", "to", "RevealEntry", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/entry.go#L204-L229
15,277
FactomProject/factom
util.go
FactoshiToFactoid
func FactoshiToFactoid(i uint64) string { d := i / 1e8 r := i % 1e8 ds := fmt.Sprintf("%d", d) rs := fmt.Sprintf("%08d", r) rs = strings.TrimRight(rs, "0") if len(rs) > 0 { ds = ds + "." } return fmt.Sprintf("%s%s", ds, rs) }
go
func FactoshiToFactoid(i uint64) string { d := i / 1e8 r := i % 1e8 ds := fmt.Sprintf("%d", d) rs := fmt.Sprintf("%08d", r) rs = strings.TrimRight(rs, "0") if len(rs) > 0 { ds = ds + "." } return fmt.Sprintf("%s%s", ds, rs) }
[ "func", "FactoshiToFactoid", "(", "i", "uint64", ")", "string", "{", "d", ":=", "i", "/", "1e8", "\n", "r", ":=", "i", "%", "1e8", "\n", "ds", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ")", "\n", "rs", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ")", "\n", "rs", "=", "strings", ".", "TrimRight", "(", "rs", ",", "\"", "\"", ")", "\n", "if", "len", "(", "rs", ")", ">", "0", "{", "ds", "=", "ds", "+", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ds", ",", "rs", ")", "\n", "}" ]
// FactoshiToFactoid converts a uint64 factoshi ammount into a fixed point // number represented as a string
[ "FactoshiToFactoid", "converts", "a", "uint64", "factoshi", "ammount", "into", "a", "fixed", "point", "number", "represented", "as", "a", "string" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/util.go#L57-L67
15,278
FactomProject/factom
util.go
FactoidToFactoshi
func FactoidToFactoshi(amt string) uint64 { valid := regexp.MustCompile(`^([0-9]+)?(\.[0-9]+)?$`) if !valid.MatchString(amt) { return 0 } var total uint64 = 0 dot := regexp.MustCompile(`\.`) pieces := dot.Split(amt, 2) whole, _ := strconv.Atoi(pieces[0]) total += uint64(whole) * 1e8 if len(pieces) > 1 { a := regexp.MustCompile(`(0*)([0-9]+)$`) as := a.FindStringSubmatch(pieces[1]) part, _ := strconv.Atoi(as[0]) power := len(as[1]) + len(as[2]) total += uint64(part * 1e8 / int(math.Pow10(power))) } return total }
go
func FactoidToFactoshi(amt string) uint64 { valid := regexp.MustCompile(`^([0-9]+)?(\.[0-9]+)?$`) if !valid.MatchString(amt) { return 0 } var total uint64 = 0 dot := regexp.MustCompile(`\.`) pieces := dot.Split(amt, 2) whole, _ := strconv.Atoi(pieces[0]) total += uint64(whole) * 1e8 if len(pieces) > 1 { a := regexp.MustCompile(`(0*)([0-9]+)$`) as := a.FindStringSubmatch(pieces[1]) part, _ := strconv.Atoi(as[0]) power := len(as[1]) + len(as[2]) total += uint64(part * 1e8 / int(math.Pow10(power))) } return total }
[ "func", "FactoidToFactoshi", "(", "amt", "string", ")", "uint64", "{", "valid", ":=", "regexp", ".", "MustCompile", "(", "`^([0-9]+)?(\\.[0-9]+)?$`", ")", "\n", "if", "!", "valid", ".", "MatchString", "(", "amt", ")", "{", "return", "0", "\n", "}", "\n\n", "var", "total", "uint64", "=", "0", "\n\n", "dot", ":=", "regexp", ".", "MustCompile", "(", "`\\.`", ")", "\n", "pieces", ":=", "dot", ".", "Split", "(", "amt", ",", "2", ")", "\n", "whole", ",", "_", ":=", "strconv", ".", "Atoi", "(", "pieces", "[", "0", "]", ")", "\n", "total", "+=", "uint64", "(", "whole", ")", "*", "1e8", "\n\n", "if", "len", "(", "pieces", ")", ">", "1", "{", "a", ":=", "regexp", ".", "MustCompile", "(", "`(0*)([0-9]+)$`", ")", "\n\n", "as", ":=", "a", ".", "FindStringSubmatch", "(", "pieces", "[", "1", "]", ")", "\n", "part", ",", "_", ":=", "strconv", ".", "Atoi", "(", "as", "[", "0", "]", ")", "\n", "power", ":=", "len", "(", "as", "[", "1", "]", ")", "+", "len", "(", "as", "[", "2", "]", ")", "\n", "total", "+=", "uint64", "(", "part", "*", "1e8", "/", "int", "(", "math", ".", "Pow10", "(", "power", ")", ")", ")", "\n", "}", "\n\n", "return", "total", "\n", "}" ]
// FactoidToFactoshi takes a Factoid amount as a string and returns the value in // factoids
[ "FactoidToFactoshi", "takes", "a", "Factoid", "amount", "as", "a", "string", "and", "returns", "the", "value", "in", "factoids" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/util.go#L71-L94
15,279
FactomProject/factom
util.go
milliTime
func milliTime() (r []byte) { buf := new(bytes.Buffer) t := time.Now().UnixNano() m := t / 1e6 binary.Write(buf, binary.BigEndian, m) return buf.Bytes()[2:] }
go
func milliTime() (r []byte) { buf := new(bytes.Buffer) t := time.Now().UnixNano() m := t / 1e6 binary.Write(buf, binary.BigEndian, m) return buf.Bytes()[2:] }
[ "func", "milliTime", "(", ")", "(", "r", "[", "]", "byte", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "t", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "m", ":=", "t", "/", "1e6", "\n", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "BigEndian", ",", "m", ")", "\n", "return", "buf", ".", "Bytes", "(", ")", "[", "2", ":", "]", "\n", "}" ]
// milliTime returns a 6 byte slice representing the unix time in milliseconds
[ "milliTime", "returns", "a", "6", "byte", "slice", "representing", "the", "unix", "time", "in", "milliseconds" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/util.go#L97-L103
15,280
FactomProject/factom
get.go
GetBalanceTotals
func GetBalanceTotals() (fSaved, fAcknowledged, eSaved, eAcknowledged int64, err error) { type multiBalanceResponse struct { FactoidAccountBalances struct { Ack int64 `json:"ack"` Saved int64 `json:"saved"` } `json:"fctaccountbalances"` EntryCreditAccountBalances struct { Ack int64 `json:"ack"` Saved int64 `json:"saved"` } `json:"ecaccountbalances"` } req := NewJSON2Request("wallet-balances", APICounter(), nil) resp, err := walletRequest(req) if err != nil { return } else if resp.Error != nil { err = resp.Error return } balances := new(multiBalanceResponse) err = json.Unmarshal(resp.JSONResult(), balances) if err != nil { return } fSaved = balances.FactoidAccountBalances.Saved fAcknowledged = balances.FactoidAccountBalances.Ack eSaved = balances.EntryCreditAccountBalances.Saved eAcknowledged = balances.EntryCreditAccountBalances.Ack return }
go
func GetBalanceTotals() (fSaved, fAcknowledged, eSaved, eAcknowledged int64, err error) { type multiBalanceResponse struct { FactoidAccountBalances struct { Ack int64 `json:"ack"` Saved int64 `json:"saved"` } `json:"fctaccountbalances"` EntryCreditAccountBalances struct { Ack int64 `json:"ack"` Saved int64 `json:"saved"` } `json:"ecaccountbalances"` } req := NewJSON2Request("wallet-balances", APICounter(), nil) resp, err := walletRequest(req) if err != nil { return } else if resp.Error != nil { err = resp.Error return } balances := new(multiBalanceResponse) err = json.Unmarshal(resp.JSONResult(), balances) if err != nil { return } fSaved = balances.FactoidAccountBalances.Saved fAcknowledged = balances.FactoidAccountBalances.Ack eSaved = balances.EntryCreditAccountBalances.Saved eAcknowledged = balances.EntryCreditAccountBalances.Ack return }
[ "func", "GetBalanceTotals", "(", ")", "(", "fSaved", ",", "fAcknowledged", ",", "eSaved", ",", "eAcknowledged", "int64", ",", "err", "error", ")", "{", "type", "multiBalanceResponse", "struct", "{", "FactoidAccountBalances", "struct", "{", "Ack", "int64", "`json:\"ack\"`", "\n", "Saved", "int64", "`json:\"saved\"`", "\n", "}", "`json:\"fctaccountbalances\"`", "\n", "EntryCreditAccountBalances", "struct", "{", "Ack", "int64", "`json:\"ack\"`", "\n", "Saved", "int64", "`json:\"saved\"`", "\n", "}", "`json:\"ecaccountbalances\"`", "\n", "}", "\n\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "nil", ")", "\n", "resp", ",", "err", ":=", "walletRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "else", "if", "resp", ".", "Error", "!=", "nil", "{", "err", "=", "resp", ".", "Error", "\n", "return", "\n", "}", "\n\n", "balances", ":=", "new", "(", "multiBalanceResponse", ")", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "balances", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "fSaved", "=", "balances", ".", "FactoidAccountBalances", ".", "Saved", "\n", "fAcknowledged", "=", "balances", ".", "FactoidAccountBalances", ".", "Ack", "\n", "eSaved", "=", "balances", ".", "EntryCreditAccountBalances", ".", "Saved", "\n", "eAcknowledged", "=", "balances", ".", "EntryCreditAccountBalances", ".", "Ack", "\n\n", "return", "\n", "}" ]
// GetBalanceTotals return the total value of Factoids and Entry Credits in the // wallet according to the the server acknowledgement and the value saved in the // blockchain.
[ "GetBalanceTotals", "return", "the", "total", "value", "of", "Factoids", "and", "Entry", "Credits", "in", "the", "wallet", "according", "to", "the", "the", "server", "acknowledgement", "and", "the", "value", "saved", "in", "the", "blockchain", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/get.go#L66-L99
15,281
FactomProject/factom
get.go
GetRate
func GetRate() (uint64, error) { type rateResponse struct { Rate uint64 `json:"rate"` } req := NewJSON2Request("entry-credit-rate", APICounter(), nil) resp, err := factomdRequest(req) if err != nil { return 0, err } if resp.Error != nil { return 0, resp.Error } rate := new(rateResponse) if err := json.Unmarshal(resp.JSONResult(), rate); err != nil { return 0, err } return rate.Rate, nil }
go
func GetRate() (uint64, error) { type rateResponse struct { Rate uint64 `json:"rate"` } req := NewJSON2Request("entry-credit-rate", APICounter(), nil) resp, err := factomdRequest(req) if err != nil { return 0, err } if resp.Error != nil { return 0, resp.Error } rate := new(rateResponse) if err := json.Unmarshal(resp.JSONResult(), rate); err != nil { return 0, err } return rate.Rate, nil }
[ "func", "GetRate", "(", ")", "(", "uint64", ",", "error", ")", "{", "type", "rateResponse", "struct", "{", "Rate", "uint64", "`json:\"rate\"`", "\n", "}", "\n\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "nil", ")", "\n", "resp", ",", "err", ":=", "factomdRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "0", ",", "resp", ".", "Error", "\n", "}", "\n\n", "rate", ":=", "new", "(", "rateResponse", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "rate", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "rate", ".", "Rate", ",", "nil", "\n", "}" ]
// GetRate returns the number of factoshis per entry credit
[ "GetRate", "returns", "the", "number", "of", "factoshis", "per", "entry", "credit" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/get.go#L102-L122
15,282
FactomProject/factom
get.go
GetDBlock
func GetDBlock(keymr string) (*DBlock, error) { params := keyMRRequest{KeyMR: keymr} req := NewJSON2Request("directory-block", APICounter(), params) resp, err := factomdRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } db := new(DBlock) if err := json.Unmarshal(resp.JSONResult(), db); err != nil { return nil, err } return db, nil }
go
func GetDBlock(keymr string) (*DBlock, error) { params := keyMRRequest{KeyMR: keymr} req := NewJSON2Request("directory-block", APICounter(), params) resp, err := factomdRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } db := new(DBlock) if err := json.Unmarshal(resp.JSONResult(), db); err != nil { return nil, err } return db, nil }
[ "func", "GetDBlock", "(", "keymr", "string", ")", "(", "*", "DBlock", ",", "error", ")", "{", "params", ":=", "keyMRRequest", "{", "KeyMR", ":", "keymr", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n", "resp", ",", "err", ":=", "factomdRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "resp", ".", "Error", "\n", "}", "\n\n", "db", ":=", "new", "(", "DBlock", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "db", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ",", "nil", "\n", "}" ]
// GetDBlock requests a Directory Block from factomd by its Key Merkle Root
[ "GetDBlock", "requests", "a", "Directory", "Block", "from", "factomd", "by", "its", "Key", "Merkle", "Root" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/get.go#L125-L142
15,283
FactomProject/factom
get.go
GetEntry
func GetEntry(hash string) (*Entry, error) { params := hashRequest{Hash: hash} req := NewJSON2Request("entry", APICounter(), params) resp, err := factomdRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } e := new(Entry) if err := json.Unmarshal(resp.JSONResult(), e); err != nil { return nil, err } return e, nil }
go
func GetEntry(hash string) (*Entry, error) { params := hashRequest{Hash: hash} req := NewJSON2Request("entry", APICounter(), params) resp, err := factomdRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } e := new(Entry) if err := json.Unmarshal(resp.JSONResult(), e); err != nil { return nil, err } return e, nil }
[ "func", "GetEntry", "(", "hash", "string", ")", "(", "*", "Entry", ",", "error", ")", "{", "params", ":=", "hashRequest", "{", "Hash", ":", "hash", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n", "resp", ",", "err", ":=", "factomdRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "resp", ".", "Error", "\n", "}", "\n\n", "e", ":=", "new", "(", "Entry", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "e", ",", "nil", "\n", "}" ]
// GetEntry requests an Entry from factomd by its Entry Hash
[ "GetEntry", "requests", "an", "Entry", "from", "factomd", "by", "its", "Entry", "Hash" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/get.go#L181-L198
15,284
FactomProject/factom
get.go
GetAllEBlockEntries
func GetAllEBlockEntries(keymr string) ([]*Entry, error) { es := make([]*Entry, 0) eb, err := GetEBlock(keymr) if err != nil { return es, err } for _, v := range eb.EntryList { e, err := GetEntry(v.EntryHash) if err != nil { return es, err } es = append(es, e) } return es, nil }
go
func GetAllEBlockEntries(keymr string) ([]*Entry, error) { es := make([]*Entry, 0) eb, err := GetEBlock(keymr) if err != nil { return es, err } for _, v := range eb.EntryList { e, err := GetEntry(v.EntryHash) if err != nil { return es, err } es = append(es, e) } return es, nil }
[ "func", "GetAllEBlockEntries", "(", "keymr", "string", ")", "(", "[", "]", "*", "Entry", ",", "error", ")", "{", "es", ":=", "make", "(", "[", "]", "*", "Entry", ",", "0", ")", "\n\n", "eb", ",", "err", ":=", "GetEBlock", "(", "keymr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "es", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "eb", ".", "EntryList", "{", "e", ",", "err", ":=", "GetEntry", "(", "v", ".", "EntryHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "es", ",", "err", "\n", "}", "\n", "es", "=", "append", "(", "es", ",", "e", ")", "\n", "}", "\n\n", "return", "es", ",", "nil", "\n", "}" ]
// GetAllEBlockEntries requests every Entry in a specific Entry Block
[ "GetAllEBlockEntries", "requests", "every", "Entry", "in", "a", "specific", "Entry", "Block" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/get.go#L243-L260
15,285
FactomProject/factom
get.go
GetEBlock
func GetEBlock(keymr string) (*EBlock, error) { params := keyMRRequest{KeyMR: keymr} req := NewJSON2Request("entry-block", APICounter(), params) resp, err := factomdRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } eb := new(EBlock) if err := json.Unmarshal(resp.JSONResult(), eb); err != nil { return nil, err } return eb, nil }
go
func GetEBlock(keymr string) (*EBlock, error) { params := keyMRRequest{KeyMR: keymr} req := NewJSON2Request("entry-block", APICounter(), params) resp, err := factomdRequest(req) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } eb := new(EBlock) if err := json.Unmarshal(resp.JSONResult(), eb); err != nil { return nil, err } return eb, nil }
[ "func", "GetEBlock", "(", "keymr", "string", ")", "(", "*", "EBlock", ",", "error", ")", "{", "params", ":=", "keyMRRequest", "{", "KeyMR", ":", "keymr", "}", "\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "params", ")", "\n", "resp", ",", "err", ":=", "factomdRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "resp", ".", "Error", "\n", "}", "\n\n", "eb", ":=", "new", "(", "EBlock", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "eb", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "eb", ",", "nil", "\n", "}" ]
// GetEBlock requests an Entry Block from factomd by its Key Merkle Root
[ "GetEBlock", "requests", "an", "Entry", "Block", "from", "factomd", "by", "its", "Key", "Merkle", "Root" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/get.go#L263-L280
15,286
FactomProject/factom
wallet/wsapi/errors.go
handleV2Error
func handleV2Error(ctx *web.Context, j *factom.JSON2Request, err *factom.JSONError) { resp := factom.NewJSON2Response() if j != nil { resp.ID = j.ID } else { resp.ID = nil } resp.Error = err ctx.WriteHeader(httpBad) ctx.Write([]byte(resp.String())) }
go
func handleV2Error(ctx *web.Context, j *factom.JSON2Request, err *factom.JSONError) { resp := factom.NewJSON2Response() if j != nil { resp.ID = j.ID } else { resp.ID = nil } resp.Error = err ctx.WriteHeader(httpBad) ctx.Write([]byte(resp.String())) }
[ "func", "handleV2Error", "(", "ctx", "*", "web", ".", "Context", ",", "j", "*", "factom", ".", "JSON2Request", ",", "err", "*", "factom", ".", "JSONError", ")", "{", "resp", ":=", "factom", ".", "NewJSON2Response", "(", ")", "\n", "if", "j", "!=", "nil", "{", "resp", ".", "ID", "=", "j", ".", "ID", "\n", "}", "else", "{", "resp", ".", "ID", "=", "nil", "\n", "}", "\n", "resp", ".", "Error", "=", "err", "\n\n", "ctx", ".", "WriteHeader", "(", "httpBad", ")", "\n", "ctx", ".", "Write", "(", "[", "]", "byte", "(", "resp", ".", "String", "(", ")", ")", ")", "\n", "}" ]
// handleV2Error handles the error responses to RPC calls
[ "handleV2Error", "handles", "the", "error", "responses", "to", "RPC", "calls" ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/wsapi/errors.go#L15-L26
15,287
FactomProject/factom
wallet/v1conversion.go
ImportV1Wallet
func ImportV1Wallet(v1path, v2path string) (*Wallet, error) { w, err := NewOrOpenBoltDBWallet(v2path) if err != nil { return nil, err } fstate := stateinit.NewFactoidState(v1path) _, values := fstate.GetDB().GetKeysValues([]byte(factoid.W_NAME)) for _, v := range values { we, ok := v.(wallet.IWalletEntry) if !ok { w.Close() return nil, fmt.Errorf("Cannot retrieve addresses from version 1 database") } switch we.GetType() { case "fct": f, err := factom.MakeFactoidAddress(we.GetPrivKey(0)[:32]) if err != nil { w.Close() return nil, err } if err := w.InsertFCTAddress(f); err != nil { w.Close() return nil, err } case "ec": e, err := factom.MakeECAddress(we.GetPrivKey(0)[:32]) if err != nil { w.Close() return nil, err } if err := w.InsertECAddress(e); err != nil { w.Close() return nil, err } default: return nil, fmt.Errorf("version 1 database returned unknown address type %s %#v", we.GetType(), we) } } return w, err }
go
func ImportV1Wallet(v1path, v2path string) (*Wallet, error) { w, err := NewOrOpenBoltDBWallet(v2path) if err != nil { return nil, err } fstate := stateinit.NewFactoidState(v1path) _, values := fstate.GetDB().GetKeysValues([]byte(factoid.W_NAME)) for _, v := range values { we, ok := v.(wallet.IWalletEntry) if !ok { w.Close() return nil, fmt.Errorf("Cannot retrieve addresses from version 1 database") } switch we.GetType() { case "fct": f, err := factom.MakeFactoidAddress(we.GetPrivKey(0)[:32]) if err != nil { w.Close() return nil, err } if err := w.InsertFCTAddress(f); err != nil { w.Close() return nil, err } case "ec": e, err := factom.MakeECAddress(we.GetPrivKey(0)[:32]) if err != nil { w.Close() return nil, err } if err := w.InsertECAddress(e); err != nil { w.Close() return nil, err } default: return nil, fmt.Errorf("version 1 database returned unknown address type %s %#v", we.GetType(), we) } } return w, err }
[ "func", "ImportV1Wallet", "(", "v1path", ",", "v2path", "string", ")", "(", "*", "Wallet", ",", "error", ")", "{", "w", ",", "err", ":=", "NewOrOpenBoltDBWallet", "(", "v2path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fstate", ":=", "stateinit", ".", "NewFactoidState", "(", "v1path", ")", "\n\n", "_", ",", "values", ":=", "fstate", ".", "GetDB", "(", ")", ".", "GetKeysValues", "(", "[", "]", "byte", "(", "factoid", ".", "W_NAME", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "values", "{", "we", ",", "ok", ":=", "v", ".", "(", "wallet", ".", "IWalletEntry", ")", "\n", "if", "!", "ok", "{", "w", ".", "Close", "(", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "we", ".", "GetType", "(", ")", "{", "case", "\"", "\"", ":", "f", ",", "err", ":=", "factom", ".", "MakeFactoidAddress", "(", "we", ".", "GetPrivKey", "(", "0", ")", "[", ":", "32", "]", ")", "\n", "if", "err", "!=", "nil", "{", "w", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "w", ".", "InsertFCTAddress", "(", "f", ")", ";", "err", "!=", "nil", "{", "w", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "e", ",", "err", ":=", "factom", ".", "MakeECAddress", "(", "we", ".", "GetPrivKey", "(", "0", ")", "[", ":", "32", "]", ")", "\n", "if", "err", "!=", "nil", "{", "w", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "w", ".", "InsertECAddress", "(", "e", ")", ";", "err", "!=", "nil", "{", "w", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "we", ".", "GetType", "(", ")", ",", "we", ")", "\n", "}", "\n", "}", "\n", "return", "w", ",", "err", "\n", "}" ]
// This file is a dirty hack to to get the keys out of a version 1 wallet. // ImportV1Wallet takes a version 1 wallet bolt.db file and imports all of its // addresses into a factom wallet.
[ "This", "file", "is", "a", "dirty", "hack", "to", "to", "get", "the", "keys", "out", "of", "a", "version", "1", "wallet", ".", "ImportV1Wallet", "takes", "a", "version", "1", "wallet", "bolt", ".", "db", "file", "and", "imports", "all", "of", "its", "addresses", "into", "a", "factom", "wallet", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet/v1conversion.go#L20-L62
15,288
FactomProject/factom
wallet.go
BackupWallet
func BackupWallet() (string, error) { type walletBackupResponse struct { Seed string `json:"wallet-seed"` Addresses []*addressResponse `json:"addresses"` IdentityKeys []*addressResponse `json:"identity-keys"` } req := NewJSON2Request("wallet-backup", APICounter(), nil) resp, err := walletRequest(req) if err != nil { return "", err } if resp.Error != nil { return "", resp.Error } w := new(walletBackupResponse) if err := json.Unmarshal(resp.JSONResult(), w); err != nil { return "", err } s := fmt.Sprintln(w.Seed) s += fmt.Sprintln() for _, adr := range w.Addresses { s += fmt.Sprintln(adr.Public) s += fmt.Sprintln(adr.Secret) s += fmt.Sprintln() } for _, k := range w.IdentityKeys { s += fmt.Sprintln(k.Public) s += fmt.Sprintln(k.Secret) s += fmt.Sprintln() } return s, nil }
go
func BackupWallet() (string, error) { type walletBackupResponse struct { Seed string `json:"wallet-seed"` Addresses []*addressResponse `json:"addresses"` IdentityKeys []*addressResponse `json:"identity-keys"` } req := NewJSON2Request("wallet-backup", APICounter(), nil) resp, err := walletRequest(req) if err != nil { return "", err } if resp.Error != nil { return "", resp.Error } w := new(walletBackupResponse) if err := json.Unmarshal(resp.JSONResult(), w); err != nil { return "", err } s := fmt.Sprintln(w.Seed) s += fmt.Sprintln() for _, adr := range w.Addresses { s += fmt.Sprintln(adr.Public) s += fmt.Sprintln(adr.Secret) s += fmt.Sprintln() } for _, k := range w.IdentityKeys { s += fmt.Sprintln(k.Public) s += fmt.Sprintln(k.Secret) s += fmt.Sprintln() } return s, nil }
[ "func", "BackupWallet", "(", ")", "(", "string", ",", "error", ")", "{", "type", "walletBackupResponse", "struct", "{", "Seed", "string", "`json:\"wallet-seed\"`", "\n", "Addresses", "[", "]", "*", "addressResponse", "`json:\"addresses\"`", "\n", "IdentityKeys", "[", "]", "*", "addressResponse", "`json:\"identity-keys\"`", "\n", "}", "\n\n", "req", ":=", "NewJSON2Request", "(", "\"", "\"", ",", "APICounter", "(", ")", ",", "nil", ")", "\n", "resp", ",", "err", ":=", "walletRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "\"", "\"", ",", "resp", ".", "Error", "\n", "}", "\n\n", "w", ":=", "new", "(", "walletBackupResponse", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "resp", ".", "JSONResult", "(", ")", ",", "w", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "s", ":=", "fmt", ".", "Sprintln", "(", "w", ".", "Seed", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", ")", "\n", "for", "_", ",", "adr", ":=", "range", "w", ".", "Addresses", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "adr", ".", "Public", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "adr", ".", "Secret", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", ")", "\n", "}", "\n", "for", "_", ",", "k", ":=", "range", "w", ".", "IdentityKeys", "{", "s", "+=", "fmt", ".", "Sprintln", "(", "k", ".", "Public", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", "k", ".", "Secret", ")", "\n", "s", "+=", "fmt", ".", "Sprintln", "(", ")", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// BackupWallet returns a formatted string with the wallet seed and the secret // keys for all of the wallet addresses.
[ "BackupWallet", "returns", "a", "formatted", "string", "with", "the", "wallet", "seed", "and", "the", "secret", "keys", "for", "all", "of", "the", "wallet", "addresses", "." ]
fc1c06ae7272973dd767b473b384c6221e74c7d7
https://github.com/FactomProject/factom/blob/fc1c06ae7272973dd767b473b384c6221e74c7d7/wallet.go#L14-L48
15,289
raff/goble
goble.go
sendCBMsg
func (ble *BLE) sendCBMsg(id int, args xpc.Dict) { message := xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args} if ble.verbose { log.Printf("sendCBMsg %#v\n", message) } ble.conn.Send(xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args}, ble.verbose) }
go
func (ble *BLE) sendCBMsg(id int, args xpc.Dict) { message := xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args} if ble.verbose { log.Printf("sendCBMsg %#v\n", message) } ble.conn.Send(xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args}, ble.verbose) }
[ "func", "(", "ble", "*", "BLE", ")", "sendCBMsg", "(", "id", "int", ",", "args", "xpc", ".", "Dict", ")", "{", "message", ":=", "xpc", ".", "Dict", "{", "\"", "\"", ":", "id", ",", "\"", "\"", ":", "args", "}", "\n", "if", "ble", ".", "verbose", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "message", ")", "\n", "}", "\n\n", "ble", ".", "conn", ".", "Send", "(", "xpc", ".", "Dict", "{", "\"", "\"", ":", "id", ",", "\"", "\"", ":", "args", "}", ",", "ble", ".", "verbose", ")", "\n", "}" ]
// send a message to Blued
[ "send", "a", "message", "to", "Blued" ]
5a206277e7359d09af80eb4519b8fa331f5ac7da
https://github.com/raff/goble/blob/5a206277e7359d09af80eb4519b8fa331f5ac7da/goble.go#L454-L461
15,290
raff/goble
goble.go
StartAdvertisingIBeacon
func (ble *BLE) StartAdvertisingIBeacon(uuid xpc.UUID, major, minor uint16, measuredPower int8) { var buf bytes.Buffer binary.Write(&buf, binary.BigEndian, uuid[:]) binary.Write(&buf, binary.BigEndian, major) binary.Write(&buf, binary.BigEndian, minor) binary.Write(&buf, binary.BigEndian, measuredPower) ble.StartAdvertisingIBeaconData(buf.Bytes()) }
go
func (ble *BLE) StartAdvertisingIBeacon(uuid xpc.UUID, major, minor uint16, measuredPower int8) { var buf bytes.Buffer binary.Write(&buf, binary.BigEndian, uuid[:]) binary.Write(&buf, binary.BigEndian, major) binary.Write(&buf, binary.BigEndian, minor) binary.Write(&buf, binary.BigEndian, measuredPower) ble.StartAdvertisingIBeaconData(buf.Bytes()) }
[ "func", "(", "ble", "*", "BLE", ")", "StartAdvertisingIBeacon", "(", "uuid", "xpc", ".", "UUID", ",", "major", ",", "minor", "uint16", ",", "measuredPower", "int8", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "uuid", "[", ":", "]", ")", "\n", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "major", ")", "\n", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "minor", ")", "\n", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "measuredPower", ")", "\n\n", "ble", ".", "StartAdvertisingIBeaconData", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// start advertising as IBeacon
[ "start", "advertising", "as", "IBeacon" ]
5a206277e7359d09af80eb4519b8fa331f5ac7da
https://github.com/raff/goble/blob/5a206277e7359d09af80eb4519b8fa331f5ac7da/goble.go#L491-L499
15,291
raff/goble
xpc/xpc.go
valueToXpc
func valueToXpc(val r.Value) C.xpc_object_t { if !val.IsValid() { return nil } var xv C.xpc_object_t switch val.Kind() { case r.Int, r.Int8, r.Int16, r.Int32, r.Int64: xv = C.xpc_int64_create(C.int64_t(val.Int())) case r.Uint, r.Uint8, r.Uint16, r.Uint32: xv = C.xpc_int64_create(C.int64_t(val.Uint())) case r.String: xv = C.xpc_string_create(C.CString(val.String())) case r.Map: xv = C.xpc_dictionary_create(nil, nil, 0) for _, k := range val.MapKeys() { v := valueToXpc(val.MapIndex(k)) C.xpc_dictionary_set_value(xv, C.CString(k.String()), v) if v != nil { C.xpc_release(v) } } case r.Array, r.Slice: if val.Type() == TYPE_OF_UUID { // Array of bytes var uuid [16]byte r.Copy(r.ValueOf(uuid[:]), val) xv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0]))) } else if val.Type() == TYPE_OF_BYTES { // slice of bytes xv = C.xpc_data_create(unsafe.Pointer(val.Pointer()), C.size_t(val.Len())) } else { xv = C.xpc_array_create(nil, 0) l := val.Len() for i := 0; i < l; i++ { v := valueToXpc(val.Index(i)) C.xpc_array_append_value(xv, v) if v != nil { C.xpc_release(v) } } } case r.Interface, r.Ptr: xv = valueToXpc(val.Elem()) default: log.Fatalf("unsupported %#v", val.String()) } return xv }
go
func valueToXpc(val r.Value) C.xpc_object_t { if !val.IsValid() { return nil } var xv C.xpc_object_t switch val.Kind() { case r.Int, r.Int8, r.Int16, r.Int32, r.Int64: xv = C.xpc_int64_create(C.int64_t(val.Int())) case r.Uint, r.Uint8, r.Uint16, r.Uint32: xv = C.xpc_int64_create(C.int64_t(val.Uint())) case r.String: xv = C.xpc_string_create(C.CString(val.String())) case r.Map: xv = C.xpc_dictionary_create(nil, nil, 0) for _, k := range val.MapKeys() { v := valueToXpc(val.MapIndex(k)) C.xpc_dictionary_set_value(xv, C.CString(k.String()), v) if v != nil { C.xpc_release(v) } } case r.Array, r.Slice: if val.Type() == TYPE_OF_UUID { // Array of bytes var uuid [16]byte r.Copy(r.ValueOf(uuid[:]), val) xv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0]))) } else if val.Type() == TYPE_OF_BYTES { // slice of bytes xv = C.xpc_data_create(unsafe.Pointer(val.Pointer()), C.size_t(val.Len())) } else { xv = C.xpc_array_create(nil, 0) l := val.Len() for i := 0; i < l; i++ { v := valueToXpc(val.Index(i)) C.xpc_array_append_value(xv, v) if v != nil { C.xpc_release(v) } } } case r.Interface, r.Ptr: xv = valueToXpc(val.Elem()) default: log.Fatalf("unsupported %#v", val.String()) } return xv }
[ "func", "valueToXpc", "(", "val", "r", ".", "Value", ")", "C", ".", "xpc_object_t", "{", "if", "!", "val", ".", "IsValid", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "var", "xv", "C", ".", "xpc_object_t", "\n\n", "switch", "val", ".", "Kind", "(", ")", "{", "case", "r", ".", "Int", ",", "r", ".", "Int8", ",", "r", ".", "Int16", ",", "r", ".", "Int32", ",", "r", ".", "Int64", ":", "xv", "=", "C", ".", "xpc_int64_create", "(", "C", ".", "int64_t", "(", "val", ".", "Int", "(", ")", ")", ")", "\n\n", "case", "r", ".", "Uint", ",", "r", ".", "Uint8", ",", "r", ".", "Uint16", ",", "r", ".", "Uint32", ":", "xv", "=", "C", ".", "xpc_int64_create", "(", "C", ".", "int64_t", "(", "val", ".", "Uint", "(", ")", ")", ")", "\n\n", "case", "r", ".", "String", ":", "xv", "=", "C", ".", "xpc_string_create", "(", "C", ".", "CString", "(", "val", ".", "String", "(", ")", ")", ")", "\n\n", "case", "r", ".", "Map", ":", "xv", "=", "C", ".", "xpc_dictionary_create", "(", "nil", ",", "nil", ",", "0", ")", "\n", "for", "_", ",", "k", ":=", "range", "val", ".", "MapKeys", "(", ")", "{", "v", ":=", "valueToXpc", "(", "val", ".", "MapIndex", "(", "k", ")", ")", "\n", "C", ".", "xpc_dictionary_set_value", "(", "xv", ",", "C", ".", "CString", "(", "k", ".", "String", "(", ")", ")", ",", "v", ")", "\n", "if", "v", "!=", "nil", "{", "C", ".", "xpc_release", "(", "v", ")", "\n", "}", "\n", "}", "\n\n", "case", "r", ".", "Array", ",", "r", ".", "Slice", ":", "if", "val", ".", "Type", "(", ")", "==", "TYPE_OF_UUID", "{", "// Array of bytes", "var", "uuid", "[", "16", "]", "byte", "\n", "r", ".", "Copy", "(", "r", ".", "ValueOf", "(", "uuid", "[", ":", "]", ")", ",", "val", ")", "\n", "xv", "=", "C", ".", "xpc_uuid_create", "(", "C", ".", "ptr_to_uuid", "(", "unsafe", ".", "Pointer", "(", "&", "uuid", "[", "0", "]", ")", ")", ")", "\n", "}", "else", "if", "val", ".", "Type", "(", ")", "==", "TYPE_OF_BYTES", "{", "// slice of bytes", "xv", "=", "C", ".", "xpc_data_create", "(", "unsafe", ".", "Pointer", "(", "val", ".", "Pointer", "(", ")", ")", ",", "C", ".", "size_t", "(", "val", ".", "Len", "(", ")", ")", ")", "\n", "}", "else", "{", "xv", "=", "C", ".", "xpc_array_create", "(", "nil", ",", "0", ")", "\n", "l", ":=", "val", ".", "Len", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "l", ";", "i", "++", "{", "v", ":=", "valueToXpc", "(", "val", ".", "Index", "(", "i", ")", ")", "\n", "C", ".", "xpc_array_append_value", "(", "xv", ",", "v", ")", "\n", "if", "v", "!=", "nil", "{", "C", ".", "xpc_release", "(", "v", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "case", "r", ".", "Interface", ",", "r", ".", "Ptr", ":", "xv", "=", "valueToXpc", "(", "val", ".", "Elem", "(", ")", ")", "\n\n", "default", ":", "log", ".", "Fatalf", "(", "\"", "\"", ",", "val", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "return", "xv", "\n", "}" ]
// valueToXpc converts a go Value to an xpc object // // note that not all the types are supported, but only the subset required for Blued
[ "valueToXpc", "converts", "a", "go", "Value", "to", "an", "xpc", "object", "note", "that", "not", "all", "the", "types", "are", "supported", "but", "only", "the", "subset", "required", "for", "Blued" ]
5a206277e7359d09af80eb4519b8fa331f5ac7da
https://github.com/raff/goble/blob/5a206277e7359d09af80eb4519b8fa331f5ac7da/xpc/xpc.go#L240-L297
15,292
raff/goble
emitter.go
Init
func (e *Emitter) Init() { e.handlers = make(map[string]EventHandlerFunc) e.event = make(chan Event) // event handler go func() { for { ev := <-e.event if fn, ok := e.handlers[ev.Name]; ok { if fn(ev) { break } } else if fn, ok := e.handlers[ALL]; ok { if fn(ev) { break } } else { if e.verbose { log.Println("unhandled Emit", ev) } } } close(e.event) // TOFIX: this causes new "emits" to panic. }() }
go
func (e *Emitter) Init() { e.handlers = make(map[string]EventHandlerFunc) e.event = make(chan Event) // event handler go func() { for { ev := <-e.event if fn, ok := e.handlers[ev.Name]; ok { if fn(ev) { break } } else if fn, ok := e.handlers[ALL]; ok { if fn(ev) { break } } else { if e.verbose { log.Println("unhandled Emit", ev) } } } close(e.event) // TOFIX: this causes new "emits" to panic. }() }
[ "func", "(", "e", "*", "Emitter", ")", "Init", "(", ")", "{", "e", ".", "handlers", "=", "make", "(", "map", "[", "string", "]", "EventHandlerFunc", ")", "\n", "e", ".", "event", "=", "make", "(", "chan", "Event", ")", "\n\n", "// event handler", "go", "func", "(", ")", "{", "for", "{", "ev", ":=", "<-", "e", ".", "event", "\n\n", "if", "fn", ",", "ok", ":=", "e", ".", "handlers", "[", "ev", ".", "Name", "]", ";", "ok", "{", "if", "fn", "(", "ev", ")", "{", "break", "\n", "}", "\n", "}", "else", "if", "fn", ",", "ok", ":=", "e", ".", "handlers", "[", "ALL", "]", ";", "ok", "{", "if", "fn", "(", "ev", ")", "{", "break", "\n", "}", "\n", "}", "else", "{", "if", "e", ".", "verbose", "{", "log", ".", "Println", "(", "\"", "\"", ",", "ev", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "close", "(", "e", ".", "event", ")", "// TOFIX: this causes new \"emits\" to panic.", "\n", "}", "(", ")", "\n", "}" ]
// Init initialize the emitter and start a goroutine to execute the event handlers
[ "Init", "initialize", "the", "emitter", "and", "start", "a", "goroutine", "to", "execute", "the", "event", "handlers" ]
5a206277e7359d09af80eb4519b8fa331f5ac7da
https://github.com/raff/goble/blob/5a206277e7359d09af80eb4519b8fa331f5ac7da/emitter.go#L38-L64
15,293
bitrise-io/go-utils
fileutil/fileutil.go
GetFileModeOfFile
func GetFileModeOfFile(pth string) (os.FileMode, error) { finfo, err := os.Lstat(pth) if err != nil { return 0, err } return finfo.Mode(), nil }
go
func GetFileModeOfFile(pth string) (os.FileMode, error) { finfo, err := os.Lstat(pth) if err != nil { return 0, err } return finfo.Mode(), nil }
[ "func", "GetFileModeOfFile", "(", "pth", "string", ")", "(", "os", ".", "FileMode", ",", "error", ")", "{", "finfo", ",", "err", ":=", "os", ".", "Lstat", "(", "pth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "finfo", ".", "Mode", "(", ")", ",", "nil", "\n", "}" ]
// GetFileModeOfFile ... // this is the "permissions" info, which can be passed directly to // functions like WriteBytesToFileWithPermission or os.OpenFile
[ "GetFileModeOfFile", "...", "this", "is", "the", "permissions", "info", "which", "can", "be", "passed", "directly", "to", "functions", "like", "WriteBytesToFileWithPermission", "or", "os", ".", "OpenFile" ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/fileutil/fileutil.go#L124-L130
15,294
bitrise-io/go-utils
stringutil/stringutil.go
MaxLastChars
func MaxLastChars(inStr string, maxCharCount int) string { return genericTrim(inStr, maxCharCount, true, false) }
go
func MaxLastChars(inStr string, maxCharCount int) string { return genericTrim(inStr, maxCharCount, true, false) }
[ "func", "MaxLastChars", "(", "inStr", "string", ",", "maxCharCount", "int", ")", "string", "{", "return", "genericTrim", "(", "inStr", ",", "maxCharCount", ",", "true", ",", "false", ")", "\n", "}" ]
// MaxLastChars returns the last maxCharCount characters, // or in case maxCharCount is more than or equal to the string's length // it'll just return the whole string.
[ "MaxLastChars", "returns", "the", "last", "maxCharCount", "characters", "or", "in", "case", "maxCharCount", "is", "more", "than", "or", "equal", "to", "the", "string", "s", "length", "it", "ll", "just", "return", "the", "whole", "string", "." ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/stringutil/stringutil.go#L37-L39
15,295
bitrise-io/go-utils
pkcs12/pkcs12.go
ToPEM
func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) { encodedPassword, err := bmpString(password) if err != nil { return nil, ErrIncorrectPassword } bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) if err != nil { return nil, err } blocks := make([]*pem.Block, 0, len(bags)) for _, bag := range bags { block, err := convertBag(&bag, encodedPassword) if err != nil { return nil, err } blocks = append(blocks, block) } return blocks, nil }
go
func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) { encodedPassword, err := bmpString(password) if err != nil { return nil, ErrIncorrectPassword } bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) if err != nil { return nil, err } blocks := make([]*pem.Block, 0, len(bags)) for _, bag := range bags { block, err := convertBag(&bag, encodedPassword) if err != nil { return nil, err } blocks = append(blocks, block) } return blocks, nil }
[ "func", "ToPEM", "(", "pfxData", "[", "]", "byte", ",", "password", "string", ")", "(", "[", "]", "*", "pem", ".", "Block", ",", "error", ")", "{", "encodedPassword", ",", "err", ":=", "bmpString", "(", "password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ErrIncorrectPassword", "\n", "}", "\n\n", "bags", ",", "encodedPassword", ",", "err", ":=", "getSafeContents", "(", "pfxData", ",", "encodedPassword", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "blocks", ":=", "make", "(", "[", "]", "*", "pem", ".", "Block", ",", "0", ",", "len", "(", "bags", ")", ")", "\n", "for", "_", ",", "bag", ":=", "range", "bags", "{", "block", ",", "err", ":=", "convertBag", "(", "&", "bag", ",", "encodedPassword", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "blocks", "=", "append", "(", "blocks", ",", "block", ")", "\n", "}", "\n\n", "return", "blocks", ",", "nil", "\n", "}" ]
// ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks.
[ "ConvertToPEM", "converts", "all", "safe", "bags", "contained", "in", "pfxData", "to", "PEM", "blocks", "." ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/pkcs12/pkcs12.go#L104-L126
15,296
bitrise-io/go-utils
pkcs12/pkcs12.go
DecodeAllCerts
func DecodeAllCerts(pfxData []byte, password string) (certificates []*x509.Certificate, err error) { encodedPassword, err := bmpString(password) if err != nil { return nil, err } bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) if err != nil { return nil, err } certificates = []*x509.Certificate{} for _, bag := range bags { switch { case bag.Id.Equal(oidCertBag): certsData, err := decodeCertBag(bag.Value.Bytes) if err != nil { return nil, err } certs, err := x509.ParseCertificates(certsData) if err != nil { return nil, err } if len(certs) != 1 { err = errors.New("pkcs12: expected exactly one certificate in the certBag") return nil, err } certificates = append(certificates, certs[0]) } } if certificates == nil || len(certificates) == 0 { return nil, errors.New("pkcs12: certificate missing") } return }
go
func DecodeAllCerts(pfxData []byte, password string) (certificates []*x509.Certificate, err error) { encodedPassword, err := bmpString(password) if err != nil { return nil, err } bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) if err != nil { return nil, err } certificates = []*x509.Certificate{} for _, bag := range bags { switch { case bag.Id.Equal(oidCertBag): certsData, err := decodeCertBag(bag.Value.Bytes) if err != nil { return nil, err } certs, err := x509.ParseCertificates(certsData) if err != nil { return nil, err } if len(certs) != 1 { err = errors.New("pkcs12: expected exactly one certificate in the certBag") return nil, err } certificates = append(certificates, certs[0]) } } if certificates == nil || len(certificates) == 0 { return nil, errors.New("pkcs12: certificate missing") } return }
[ "func", "DecodeAllCerts", "(", "pfxData", "[", "]", "byte", ",", "password", "string", ")", "(", "certificates", "[", "]", "*", "x509", ".", "Certificate", ",", "err", "error", ")", "{", "encodedPassword", ",", "err", ":=", "bmpString", "(", "password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bags", ",", "encodedPassword", ",", "err", ":=", "getSafeContents", "(", "pfxData", ",", "encodedPassword", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "certificates", "=", "[", "]", "*", "x509", ".", "Certificate", "{", "}", "\n", "for", "_", ",", "bag", ":=", "range", "bags", "{", "switch", "{", "case", "bag", ".", "Id", ".", "Equal", "(", "oidCertBag", ")", ":", "certsData", ",", "err", ":=", "decodeCertBag", "(", "bag", ".", "Value", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "certs", ",", "err", ":=", "x509", ".", "ParseCertificates", "(", "certsData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "certs", ")", "!=", "1", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "certificates", "=", "append", "(", "certificates", ",", "certs", "[", "0", "]", ")", "\n", "}", "\n", "}", "\n\n", "if", "certificates", "==", "nil", "||", "len", "(", "certificates", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// DecodeAllCerts extracts a certificates from pfxData.
[ "DecodeAllCerts", "extracts", "a", "certificates", "from", "pfxData", "." ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/pkcs12/pkcs12.go#L271-L307
15,297
bitrise-io/go-utils
sliceutil/sliceutil.go
UniqueStringSlice
func UniqueStringSlice(strs []string) []string { lookupMap := map[string]interface{}{} for _, aStr := range strs { lookupMap[aStr] = 1 } uniqueStrs := []string{} for k := range lookupMap { uniqueStrs = append(uniqueStrs, k) } return uniqueStrs }
go
func UniqueStringSlice(strs []string) []string { lookupMap := map[string]interface{}{} for _, aStr := range strs { lookupMap[aStr] = 1 } uniqueStrs := []string{} for k := range lookupMap { uniqueStrs = append(uniqueStrs, k) } return uniqueStrs }
[ "func", "UniqueStringSlice", "(", "strs", "[", "]", "string", ")", "[", "]", "string", "{", "lookupMap", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "aStr", ":=", "range", "strs", "{", "lookupMap", "[", "aStr", "]", "=", "1", "\n", "}", "\n", "uniqueStrs", ":=", "[", "]", "string", "{", "}", "\n", "for", "k", ":=", "range", "lookupMap", "{", "uniqueStrs", "=", "append", "(", "uniqueStrs", ",", "k", ")", "\n", "}", "\n", "return", "uniqueStrs", "\n", "}" ]
// UniqueStringSlice - returns a cleaned up list, // where every item is unique. // Does NOT guarantee any ordering, the result can // be in any order!
[ "UniqueStringSlice", "-", "returns", "a", "cleaned", "up", "list", "where", "every", "item", "is", "unique", ".", "Does", "NOT", "guarantee", "any", "ordering", "the", "result", "can", "be", "in", "any", "order!" ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/sliceutil/sliceutil.go#L7-L17
15,298
bitrise-io/go-utils
command/git/git.go
New
func New(dir string) (Git, error) { if err := os.MkdirAll(dir, 0755); err != nil { return Git{}, err } return Git{dir: dir}, nil }
go
func New(dir string) (Git, error) { if err := os.MkdirAll(dir, 0755); err != nil { return Git{}, err } return Git{dir: dir}, nil }
[ "func", "New", "(", "dir", "string", ")", "(", "Git", ",", "error", ")", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "Git", "{", "}", ",", "err", "\n", "}", "\n", "return", "Git", "{", "dir", ":", "dir", "}", ",", "nil", "\n", "}" ]
// New creates a new git project.
[ "New", "creates", "a", "new", "git", "project", "." ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/command/git/git.go#L15-L20
15,299
bitrise-io/go-utils
pathutil/pathutil.go
AbsPath
func AbsPath(pth string) (string, error) { if pth == "" { return "", errors.New("No Path provided") } pth, err := ExpandTilde(pth) if err != nil { return "", err } return filepath.Abs(os.ExpandEnv(pth)) }
go
func AbsPath(pth string) (string, error) { if pth == "" { return "", errors.New("No Path provided") } pth, err := ExpandTilde(pth) if err != nil { return "", err } return filepath.Abs(os.ExpandEnv(pth)) }
[ "func", "AbsPath", "(", "pth", "string", ")", "(", "string", ",", "error", ")", "{", "if", "pth", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "pth", ",", "err", ":=", "ExpandTilde", "(", "pth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "filepath", ".", "Abs", "(", "os", ".", "ExpandEnv", "(", "pth", ")", ")", "\n", "}" ]
// AbsPath expands ENV vars and the ~ character // then call Go's Abs
[ "AbsPath", "expands", "ENV", "vars", "and", "the", "~", "character", "then", "call", "Go", "s", "Abs" ]
2a09aab8380d7842750328aebd5671bcccea89c8
https://github.com/bitrise-io/go-utils/blob/2a09aab8380d7842750328aebd5671bcccea89c8/pathutil/pathutil.go#L111-L122