text
stringlengths
11
4.05M
package validator import ( "errors" "fmt" "net/http" "time" "github.com/gin-gonic/gin" ) const maxTimeGap = 30 * time.Second // 30 secs func newPublicError(msg string) *gin.Error { return &gin.Error{ Err: errors.New(msg), Type: gin.ErrorTypePublic, } } // ErrDateNotInRange error when date not in acceptable range var ErrDateNotInRange = newPublicError("Date submit is not in acceptable range") // DateValidator checking validate by time range type DateValidator struct { // TimeGap is max time different between client submit timestamp // and server time that considered valid. The time precision is millisecond. TimeGap time.Duration } // NewDateValidator return DateValidator with default value (30 second) func NewDateValidator() *DateValidator { return &DateValidator{ TimeGap: maxTimeGap, } } // Validate return error when checking if header date is valid or not func (v *DateValidator) Validate(r *http.Request) error { t, err := http.ParseTime(r.Header.Get("date")) if err != nil { return newPublicError(fmt.Sprintf("Could not parse date header. Error: %s", err.Error())) } serverTime := time.Now() start := serverTime.Add(-v.TimeGap) stop := serverTime.Add(v.TimeGap) if t.Before(start) || t.After(stop) { return ErrDateNotInRange } return nil }
package main import ( "fmt" "io/ioutil" "log" "os" "strings" ) func main() { orbits := readFile() f, b := parseMap(orbits) d := map[string]int{} findDistanceFrom("COM", 0, f, d) totalOrbits := 0 for _, distance := range d { totalOrbits += distance } // Part 1 solution fmt.Println("Total orbis", totalOrbits) var ( youBackrefs = backrefsFor("YOU", b, map[string]struct{}{}) sanBackrefs = backrefsFor("SAN", b, map[string]struct{}{}) commonKeys = []string{} nearestSharedDistance = 0 ) // Check common keys found as backrefs from both 'YOU' and 'SAN'. for k := range youBackrefs { if _, ok := sanBackrefs[k]; ok { commonKeys = append(commonKeys, k) } } // Iterate over the common ones and find the distance to the one closest to // you/farthest 'COM'. for _, k := range commonKeys { if nearestSharedDistance == 0 || d[k] > nearestSharedDistance { nearestSharedDistance = d[k] } } // Add the distance between 'YOU' and the closest shared + the distance // between 'SAN' and the closest shared one to get a delta. srcMinusNearest := len(youBackrefs) - nearestSharedDistance dstMinusNearest := len(sanBackrefs) - nearestSharedDistance delta := srcMinusNearest + dstMinusNearest - 2 // Remove 'YOU' and 'SAN'. // Part 2 solution fmt.Println("Minimum orbits to move between 'YOU' and 'SAN':", delta) } func backrefsFor(planet string, backrefs map[string]string, m map[string]struct{}) map[string]struct{} { backref, ok := backrefs[planet] if !ok { return m } m[backref] = struct{}{} return backrefsFor(backref, backrefs, m) } func findDistanceFrom(planet string, distance int, orbits map[string][]string, store map[string]int) { store[planet] = distance nextDistance := distance + 1 f, ok := orbits[planet] if !ok { return } for _, p := range f { findDistanceFrom(p, nextDistance, orbits, store) } } func parseMap(orbits []string) (map[string][]string, map[string]string) { var ( forward = map[string][]string{} backward = map[string]string{} ) for _, line := range orbits { parts := strings.Split(line, ")") lhs, rhs := parts[0], parts[1] forward[lhs] = append(forward[lhs], rhs) backward[rhs] = lhs } return forward, backward } func readFile() []string { if len(os.Args) < 2 { log.Fatal("missing file as input") } line, err := ioutil.ReadFile(os.Args[1]) if err != nil { log.Fatalf("could not read file: %s", err.Error()) } return strings.Split(strings.TrimSpace(string(line)), "\n") }
package imap import ( "context" "crypto/tls" "fmt" "regexp" "strings" "time" "golang.org/x/exp/slices" "github.com/mitchellh/mapstructure" "github.com/ovh/venom" "github.com/pkg/errors" "github.com/yesnault/go-imap/imap" ) const ( // Name for test imap Name = "imap" // imapClientTimeout represents the timeout for the IMAP client and, as a result, the timeout for the testcase imapClientTimeout = 5 * time.Second ) var ( imapLogMask = imap.LogNone imapSafeLogMask = imap.LogNone errMailNotFound = errors.New("mail not found") errEmptyMailbox = errors.New("empty mailbox") ) // New returns a new Test Exec func New() venom.Executor { return &Executor{} } type CommandName string const ( // CommandAppend creates a new message at the end of a specified mailbox. CommandAppend CommandName = "append" // CommandCreate creates a new mailbox. CommandCreate CommandName = "create" // CommandClear permanently removes all messages from given mailboxes. CommandClear CommandName = "clear" // CommandDelete permanently removes a message retrieved through Search field CommandDelete CommandName = "delete" // CommandFetch retrieves a mail through Search field (no args) CommandFetch CommandName = "fetch" // CommandFlag adds, removes or sets flags to a message retrieved through Search field CommandFlag CommandName = "flag" // CommandMove moves a message retrieved through Search field from one mailbox to another. CommandMove CommandName = "move" ) // commandAppendArgs represents the arguments to the append command. // from and mailbox are mandatory fields type commandAppendArgs struct { mailbox string from string to string subject string body string flags []string } func (a *commandAppendArgs) initFrom(args map[string]any) { if v, ok := args["mailbox"]; ok { a.mailbox = v.(string) } if v, ok := args["from"]; ok { a.from = v.(string) } if v, ok := args["to"]; ok { a.to = v.(string) } if v, ok := args["subject"]; ok { a.subject = v.(string) } if v, ok := args["body"]; ok { a.body = v.(string) } if v, ok := args["flags"]; ok { flagsAny := v.([]any) flagsStr := make([]string, len(flagsAny)) for i, mailbox := range flagsAny { flagsStr[i] = mailbox.(string) } a.flags = flagsStr } } func (a *commandAppendArgs) isAnyMandatoryFieldEmpty() bool { return a.mailbox == "" || a.from == "" } // commandCreateArgs represents the arguments to the create command type commandCreateArgs struct { // The name of the mailbox to create mailbox string } func (a *commandCreateArgs) initFrom(args map[string]any) { if v, ok := args["mailbox"]; ok { a.mailbox = v.(string) } } func (a *commandCreateArgs) isAnyMandatoryFieldEmpty() bool { return a.mailbox == "" } // commandClearArgs represents the arguments to the clear command type commandClearArgs struct { // The names of the mailboxes to create mailboxes []string } func (a *commandClearArgs) initFrom(args map[string]any) { if v, ok := args["mailboxes"]; ok { mailboxesAny := v.([]any) mailboxesStr := make([]string, len(mailboxesAny)) for i, mailbox := range mailboxesAny { mailboxesStr[i] = mailbox.(string) } a.mailboxes = mailboxesStr } } func (a *commandClearArgs) isAnyMandatoryFieldEmpty() bool { return len(a.mailboxes) == 0 } // commandFlagArgs represents the arguments to the flag command. // One of add, remove or set fields is mandatory type commandFlagArgs struct { // add new flags to the mail add []string // remove flags from the mail remove []string // set mail flags (overwrites current mail flags). // If set is not empty, add and remove fields will not be considered set []string } func (a *commandFlagArgs) initFrom(args map[string]any) { if v, ok := args["add"]; ok { addAny := v.([]any) AddStr := make([]string, len(addAny)) for i, mailbox := range addAny { AddStr[i] = mailbox.(string) } a.add = AddStr } if v, ok := args["remove"]; ok { removeAny := v.([]any) RemoveStr := make([]string, len(removeAny)) for i, mailbox := range removeAny { RemoveStr[i] = mailbox.(string) } a.remove = RemoveStr } if v, ok := args["set"]; ok { setAny := v.([]any) SetStr := make([]string, len(setAny)) for i, mailbox := range setAny { SetStr[i] = mailbox.(string) } a.set = SetStr } } func (a *commandFlagArgs) isEmpty() bool { return len(a.add)+len(a.remove)+len(a.set) == 0 } // commandMoveArgs represents the arguments to the move command. // mailbox is a mandatory field type commandMoveArgs struct { // The name of the mailbox to move the mail to mailbox string } func (a *commandMoveArgs) initFrom(args map[string]any) { if v, ok := args["mailbox"]; ok { a.mailbox = v.(string) } } func (a *commandMoveArgs) isAnyMandatoryFieldEmpty() bool { return a.mailbox == "" } // SearchCriteria represents the search criteria to fetch mails through FETCH command (https://www.rfc-editor.org/rfc/rfc3501#section-6.4.5) type SearchCriteria struct { Mailbox string `json:"mailbox,omitempty" yaml:"mailbox,omitempty"` UID uint32 `json:"uid,omitempty" yaml:"uid,omitempty"` From string `json:"from,omitempty" yaml:"from,omitempty"` To string `json:"to,omitempty" yaml:"to,omitempty"` Subject string `json:"subject,omitempty" yaml:"subject,omitempty"` Body string `json:"body,omitempty" yaml:"body,omitempty"` } func (s *SearchCriteria) isAnyMandatoryFieldEmpty() bool { return s.Mailbox == "" } // Command represents a command that can be performed to messages or mailboxes. type Command struct { // Search defines the search criteria to retrieve a mail. Some commands need to act upon a mail retrieved through Search. Search SearchCriteria `json:"search" yaml:"search"` // Name defines an IMAP command to execute. Name CommandName `json:"name" yaml:"name"` // Args defines the arguments to the command. Arguments associated to the command are listed in the README file Args map[string]any `json:"args" yaml:"args"` } type Mail struct { UID uint32 `json:"uid,omitempty" yaml:"uid,omitempty"` From string `json:"from,omitempty" yaml:"from,omitempty"` To string `json:"to,omitempty" yaml:"to,omitempty"` Subject string `json:"subject,omitempty" yaml:"subject,omitempty"` Body string `json:"body,omitempty" yaml:"body,omitempty"` Flags []string `json:"flags,omitempty" yaml:"flags,omitempty"` } func (m *Mail) containsFlag(flag string) bool { for _, mFlag := range m.Flags { if flag == mFlag { return true } } return false } func (m *Mail) containsFlags(flags []string) bool { for _, flag := range flags { found := m.containsFlag(flag) if !found { return false } } return true } // containsAnyButSeenOrRecent returns true if m contains any flag in flags (except "\Seen" or "\Recent") func (m *Mail) containsAnyButSeenOrRecent(flags []string) bool { for _, flag := range flags { if flag == `\Seen` || flag == `\Recent` { continue } found := m.containsFlag(flag) if found { return true } } return false } func (m *Mail) hasSameFlags(flags []string) bool { slices.Sort(m.Flags) slices.Sort(flags) return slices.Equal(m.Flags, flags) } // CommandResult contains the results of a command with the states of the mail before and after the command. type CommandResult struct { // Search represents the result of the Command's search field Search Mail `json:"search,omitempty" yaml:"search,omitempty"` // Mail represents the state of the searched mail after the command was executed Mail Mail `json:"mail,omitempty" yaml:"mail,omitempty"` Err string `json:"err,omitempty" yaml:"err,omitempty"` TimeSeconds float64 `json:"timeseconds,omitempty" yaml:"timeseconds,omitempty"` } // Result represents a step result. It contains the results of every command that was executed type Result struct { Commands []CommandResult `json:"commands,omitempty" yaml:"commands,omitempty"` } type Client struct { *imap.Client } type AuthConfig struct { WithTLS bool `json:"withtls,omitempty" yaml:"withtls,omitempty"` Host string `json:"host,omitempty" yaml:"host,omitempty"` Port string `json:"port,omitempty" yaml:"port,omitempty"` User string `json:"user,omitempty" yaml:"user,omitempty"` Password string `json:"password,omitempty" yaml:"password,omitempty"` } // Executor represents a Test Executor type Executor struct { Auth AuthConfig `json:"auth" yaml:"auth"` Commands []Command `json:"commands,omitempty" yaml:"commands,omitempty"` } // ZeroValueResult return an empty implementation of this executor result func (Executor) ZeroValueResult() interface{} { return Result{} } // GetDefaultAssertions return default assertions for type imap func (Executor) GetDefaultAssertions() *venom.StepAssertions { return &venom.StepAssertions{Assertions: []venom.Assertion{"result.err ShouldBeEmpty"}} } // Run execute TestStep of type exec func (Executor) Run(ctx context.Context, step venom.TestStep) (interface{}, error) { var e Executor if err := mapstructure.Decode(step, &e); err != nil { return nil, err } c, err := e.connect(e.Auth.Host, e.Auth.Port, e.Auth.User, e.Auth.Password) if err != nil { return nil, fmt.Errorf("Error while connecting: %w", err) } defer c.Logout(imapClientTimeout) // nolint client := &Client{c} result := Result{} result.Commands = e.handleCommands(ctx, client) return result, nil } // handleCommands executes every Command from Executor and returns their result func (e Executor) handleCommands(ctx context.Context, c *Client) []CommandResult { var results = make([]CommandResult, len(e.Commands)) for i, command := range e.Commands { switch command.Name { case CommandAppend: args := commandAppendArgs{} args.initFrom(command.Args) results[i] = c.appendMail(ctx, args) case CommandClear: args := commandClearArgs{} args.initFrom(command.Args) results[i] = c.clearMailboxes(ctx, args) case CommandCreate: args := commandCreateArgs{} args.initFrom(command.Args) results[i] = c.createMailbox(ctx, args) case CommandDelete: results[i] = c.deleteMail(ctx, command.Search) case CommandFetch: results[i] = c.fetchMail(ctx, command.Search) case CommandFlag: args := commandFlagArgs{} args.initFrom(command.Args) results[i] = c.flagMail(ctx, command.Search, args) case CommandMove: args := commandMoveArgs{} args.initFrom(command.Args) results[i] = c.moveMail(ctx, command.Search, args) default: results[i].Err = "unknown command" } if results[i].Err != "" { venom.Debug(ctx, fmt.Sprintf("Failed to handle command %s: %s", command.Name, results[i].Err)) } } return results } // clearMailboxes clears the given mailbox. If mailbox is '*', clears all mailboxes. func (c *Client) clearMailboxes(ctx context.Context, args commandClearArgs) CommandResult { start := time.Now() result := CommandResult{} if args.mailboxes[0] == "*" { venom.Debug(ctx, "\"*\" argument found, clearing all mailboxes") cmd, err := imap.Wait(c.List("", "*")) if err != nil { return CommandResult{Err: fmt.Sprintf("Error while retrieving mailboxes: %v", err)} } mailboxes := make([]string, len(cmd.Data)) for i, rsp := range cmd.Data { mailboxes[i] = rsp.MailboxInfo().Name } args.mailboxes = mailboxes } for _, mailbox := range args.mailboxes { err := c.clearMailbox(ctx, mailbox) if err != nil { return CommandResult{Err: err.Error()} } } result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Clear command executed in %.2f seconds", result.TimeSeconds) return result } func (c *Client) clearMailbox(ctx context.Context, mailbox string) error { venom.Debug(ctx, "Clearing mailbox %q", mailbox) seq, err := imap.NewSeqSet("1:*") if err != nil { return fmt.Errorf("error while building request to select all messages: %v", err) } venom.Debug(ctx, "Selecting mailbox %q", mailbox) if _, err = c.Select(mailbox, false); err != nil { return fmt.Errorf("error while selecting mailbox %q: %v", mailbox, err) } venom.Debug(ctx, "Adding tag '\\Deleted' to all messages") _, err = imap.Wait(c.UIDStore(seq, "+FLAGS.SILENT", imap.NewFlagSet(`\Deleted`))) if err != nil { return fmt.Errorf("error while adding flag '\\Deleted' to all messages in mailbox %q: %v", mailbox, err) } venom.Debug(ctx, "Expunging mailbox") if _, err = imap.Wait(c.Expunge(seq)); err != nil { return fmt.Errorf("error while expunging mails in mailbox %q: %v", mailbox, err) } // Command execution verifications venom.Debug(ctx, "Searching mails in mailbox %q to make sure they were all deleted", mailbox) count, err := c.countNumberOfMessagesInMailbox(mailbox) if err != nil { return fmt.Errorf("error while counting number of messages in mailbox %q after clear command: %v", mailbox, err) } if count > 0 { return fmt.Errorf("%d message(s) were found in mailbox %q", count, mailbox) } else { venom.Debug(ctx, "No message found in mailbox %q: clear command successfully completed!", mailbox) } return nil } func (c *Client) appendMail(ctx context.Context, args commandAppendArgs) CommandResult { start := time.Now() result := CommandResult{} message := []string{ fmt.Sprintf("From: %s", args.from), fmt.Sprintf("Subject: %s", args.subject), fmt.Sprintf("To: %s", args.to), "Content-Type: text/plain; charset=utf-8", "", args.body, "", } messageBytes := []byte(strings.Join(message, "\r\n")) literal := imap.NewLiteral(messageBytes) flags := imap.NewFlagSet(args.flags...) venom.Debug(ctx, "Appending message with fields: %+v", args) _, err := imap.Wait(c.Append(args.mailbox, flags, nil, literal)) if err != nil { return CommandResult{Err: fmt.Sprintf("Error while appending message: %v", err)} } venom.Debug(ctx, "Successfully appended message!") // Command execution verifications venom.Debug(ctx, "Searching mail to make sure it was created") mail, err := c.getFirstFoundMail(ctx, SearchCriteria{ Mailbox: args.mailbox, From: args.from, To: args.to, Subject: args.subject, Body: args.body, }) if err != nil { result.Err = fmt.Sprintf("Error while retrieving mail after append command was executed: %v", err) venom.Error(ctx, result.Err) } else { venom.Debug(ctx, "Mail was retrieved: append command successfully completed") result.Mail = mail } result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Append command executed in %.2f seconds", result.TimeSeconds) return result } func (c *Client) createMailbox(ctx context.Context, args commandCreateArgs) CommandResult { start := time.Now() result := CommandResult{} venom.Debug(ctx, "Creating mailbox %q", args.mailbox) _, err := c.Create(args.mailbox) if err != nil { return CommandResult{Err: fmt.Sprintf("Error while creating mailbox: %v", err)} } venom.Debug(ctx, "Successfully created mailbox!") // Command execution verifications venom.Debug(ctx, "Selecting mailbox after command to make sure it exists") _, err = imap.Wait(c.Status(args.mailbox)) if err != nil { return CommandResult{Err: fmt.Sprintf("Error while waiting mailbox status after create command was executed: %v", err)} } venom.Debug(ctx, "Mailbox was indeed created: create command successfully completed!") result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Create command executed in %.2f seconds", result.TimeSeconds) return result } func (c *Client) flagMail(ctx context.Context, mailToFind SearchCriteria, args commandFlagArgs) CommandResult { start := time.Now() result := CommandResult{} // As setting flags overrides any existing one, there is no need to add or remove flags if 'set' field is set if len(args.set) > 0 { result = c.setFlagsOfMail(ctx, mailToFind, args.set) } else { if len(args.add) > 0 { result = c.addFlagsToMail(ctx, mailToFind, args.add) } if len(args.remove) > 0 { result = c.removeFlagsFromMail(ctx, mailToFind, args.remove) } } result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Flag command executed in %.2f seconds", result.TimeSeconds) return result } // addFlagsToMail adds the flags contained in flags to the retrieved mail func (c *Client) addFlagsToMail(ctx context.Context, mailToFind SearchCriteria, flags []string) CommandResult { result := CommandResult{} venom.Debug(ctx, "Searching mail with criteria: %+v", mailToFind) mail, err := c.getFirstFoundMail(ctx, mailToFind) if err != nil { return CommandResult{Err: fmt.Sprintf("add: error while retrieving mail: %v", err)} } result.Search = mail seq, _ := imap.NewSeqSet("") seq.AddNum(mail.UID) venom.Debug(ctx, "Adding following flags from mail: %v", flags) _, err = imap.Wait(c.UIDStore(seq, "+FLAGS.SILENT", imap.NewFlagSet(flags...))) if err != nil { result.Err = fmt.Sprintf("add: error while calling UID Store command: %v", err) return result } venom.Debug(ctx, "Successfully added flags to mail!") // Making sure new flags are the expected ones mail, err = c.getFirstFoundMail(ctx, mailToFind) if err != nil { result.Err = fmt.Sprintf("add: error while retrieving mail: %v", err) return result } result.Mail = mail if !result.Mail.containsFlags(flags) { result.Err = fmt.Sprintf("add: mail has flags %v while it should contain flags %v", mail.Flags, flags) return result } return result } // removeFlagsFromMail removes the flags contained in flags from the retrieved mail func (c *Client) removeFlagsFromMail(ctx context.Context, mailToFind SearchCriteria, flags []string) CommandResult { result := CommandResult{} venom.Debug(ctx, "Searching mail with criteria: %+v", mailToFind) mail, err := c.getFirstFoundMail(ctx, mailToFind) if err != nil { return CommandResult{Err: fmt.Sprintf("remove: error while retrieving mail: %v", err)} } result.Search = mail seq, _ := imap.NewSeqSet("") seq.AddNum(mail.UID) venom.Debug(ctx, "Removing following flags from mail: %v", flags) _, err = imap.Wait(c.UIDStore(seq, "-FLAGS.SILENT", imap.NewFlagSet(flags...))) if err != nil { result.Err = fmt.Sprintf("remove: error while calling UID Store command: %v", err) return result } venom.Debug(ctx, "Successfully removed flags from mail!") // Making sure new flags are the expected ones mail, err = c.getFirstFoundMail(ctx, mailToFind) if err != nil { result.Err = fmt.Sprintf("remove: error while retrieving mail: %v", err) return result } result.Mail = mail // Fetching the mail and reading its text section added the "\Seen" flag. if result.Mail.containsAnyButSeenOrRecent(flags) { result.Err = fmt.Sprintf("remove: mail has flags %v while it should not have flags %v", mail.Flags, flags) return result } return result } // setFlagsOfMail sets the flags of the retrieved mail from flags func (c *Client) setFlagsOfMail(ctx context.Context, mailToFind SearchCriteria, flags []string) CommandResult { result := CommandResult{} venom.Debug(ctx, "Searching mail with criteria: %+v", mailToFind) mail, err := c.getFirstFoundMail(ctx, mailToFind) if err != nil { return CommandResult{Err: fmt.Sprintf("set: error while retrieving mail: %v", err)} } result.Search = mail seq, _ := imap.NewSeqSet("") seq.AddNum(mail.UID) venom.Debug(ctx, "Setting following mail flags: %v", flags) _, err = imap.Wait(c.UIDStore(seq, "FLAGS.SILENT", imap.NewFlagSet(flags...))) if err != nil { result.Err = fmt.Sprintf("set: error while calling UID Store command: %v", err) return result } venom.Debug(ctx, "Successfully set mail flags!") // Making sure new flags are the expected ones mail, err = c.getFirstFoundMail(ctx, mailToFind) if err != nil { result.Err = fmt.Sprintf("set: error while retrieving mail: %v", err) return result } result.Mail = mail // Fetching the mail and reading its text section added the "\Seen" flag. flags = append(flags, `\Seen`) if !result.Mail.hasSameFlags(flags) { result.Err = fmt.Sprintf("set: mail has flags %v while it should have flags %v", mail.Flags, flags) return result } return result } func (c *Client) fetchMail(ctx context.Context, mailToFind SearchCriteria) CommandResult { start := time.Now() result := CommandResult{} venom.Debug(ctx, "Searching mail with criteria: %+v", mailToFind) mail, err := c.getFirstFoundMail(ctx, mailToFind) if err != nil { return CommandResult{Err: fmt.Sprintf("error while retrieving mail: %v", err)} } venom.Debug(ctx, "Found mail: %+v", mail) // To avoid confusing the user about whether field to test, both are valid as the command does not modify the mail result.Search = mail result.Mail = mail result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Move command executed in %.2f seconds", result.TimeSeconds) return result } func (c *Client) deleteMail(ctx context.Context, mailToFind SearchCriteria) CommandResult { start := time.Now() result := CommandResult{} venom.Debug(ctx, "Searching mail with criteria: %+v", mailToFind) mail, err := c.getFirstFoundMail(ctx, mailToFind) if err != nil { return CommandResult{Err: fmt.Sprintf("error while retrieving mail: %v", err)} } venom.Debug(ctx, "Found mail: %+v", mail) result.Search = mail seq, _ := imap.NewSeqSet("") seq.AddNum(mail.UID) venom.Debug(ctx, "Selecting mailbox %q", mailToFind.Mailbox) if _, err = c.Select(mailToFind.Mailbox, false); err != nil { result.Err = fmt.Sprintf("Error while selecting mailbox %q: %v", mailToFind.Mailbox, err) return result } venom.Debug(ctx, "Adding flag '\\Deleted' to mail") if _, err = imap.Wait(c.UIDStore(seq, "+FLAGS.SILENT", imap.NewFlagSet(`\Deleted`))); err != nil { result.Err = fmt.Sprintf("Error while adding '\\Deleted' flag to mail %d: %v", mail.UID, err) return result } venom.Debug(ctx, "Expunging mailbox %q", mailToFind.Mailbox) if _, err = imap.Wait(c.Expunge(seq)); err != nil { result.Err = fmt.Sprintf("Error while expunging mailbox %q: %v", mailToFind.Mailbox, err) return result } venom.Debug(ctx, "Mailbox successfully expunged") // Command execution verifications venom.Debug(ctx, "Searching mail to make sure it was deleted") mailToFind.UID = mail.UID mail, err = c.getFirstFoundMail(ctx, mailToFind) if err != nil && (err == errMailNotFound || err == errEmptyMailbox) { venom.Debug(ctx, "Mail was successfully deleted: delete command successfully completed!") } else if err == nil { result.Err = "Supposedly deleted mail was found after delete command was executed" venom.Error(ctx, result.Err) result.Mail = mail } else { result.Err = fmt.Sprintf("Error while trying to confirm mail was deleted: %v", err) venom.Warn(ctx, result.Err) } result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Delete command executed in %.2f seconds", result.TimeSeconds) return result } func (c *Client) moveMail(ctx context.Context, mailToFind SearchCriteria, args commandMoveArgs) CommandResult { start := time.Now() result := CommandResult{} venom.Debug(ctx, "Searching mail with criteria: %+v", mailToFind) mail, err := c.getFirstFoundMail(ctx, mailToFind) if err != nil { return CommandResult{Err: fmt.Sprintf("error while retrieving mail: %v", err)} } venom.Debug(ctx, "Found mail: %+v", mail) result.Search = mail seq, _ := imap.NewSeqSet("") seq.AddNum(mail.UID) venom.Debug(ctx, "Moving message to mailbox %q", mailToFind.Mailbox) if _, err = imap.Wait(c.UIDMove(seq, args.mailbox)); err != nil { return CommandResult{Err: fmt.Sprintf("Error while selecting mailbox %q: %v", mailToFind.Mailbox, err)} } venom.Debug(ctx, "Successfully moved message to mailbox %q", mailToFind.Mailbox) // Command execution verifications venom.Debug(ctx, "Searching mail to make sure it was moved") mailToFind.Mailbox = args.mailbox mail, err = c.getFirstFoundMail(ctx, mailToFind) if err != nil { result.Err = fmt.Sprintf("Error while trying to confirm mail was moved: %v", err) venom.Warn(ctx, result.Err) } result.Mail = mail venom.Debug(ctx, "Mail was successfully moved: move command successfully completed!") result.TimeSeconds = time.Since(start).Seconds() venom.Debug(ctx, "Move command executed in %.2f seconds", result.TimeSeconds) return result } func (m *Mail) isSearched(mailToFind SearchCriteria) (bool, error) { var ( matched bool err error ) if mailToFind.UID != 0 { if mailToFind.UID != m.UID { return false, nil } } if mailToFind.From != "" { matched, err = regexp.MatchString(mailToFind.From, m.From) if err != nil || !matched { return false, err } } if mailToFind.To != "" { matched, err = regexp.MatchString(mailToFind.To, m.To) if err != nil || !matched { return false, err } } if mailToFind.Subject != "" { matched, err = regexp.MatchString(mailToFind.Subject, m.Subject) if err != nil || !matched { return false, err } } if mailToFind.Body != "" { // Remove all new line, return and tab characters that can make the match fail replacer := strings.NewReplacer("\n", "", "\r", "", "\t", "") m.Body = replacer.Replace(m.Body) mailToFind.Body = replacer.Replace(mailToFind.Body) matched, err = regexp.MatchString(mailToFind.Body, m.Body) if err != nil || !matched { return false, err } } return true, nil } // getFirstFoundMail returns the first mail found through search criteria // If peek is true, mail body text will not be read thus leaving flags unchanged (for more information, refer to RFC 3501 section 6.4.5) func (c *Client) getFirstFoundMail(ctx context.Context, mailToFind SearchCriteria) (Mail, error) { if mailToFind.isAnyMandatoryFieldEmpty() { return Mail{}, errors.New("empty search criteria: 'mailbox' is a mandatory field") } count, err := c.countNumberOfMessagesInMailbox(mailToFind.Mailbox) if err != nil { return Mail{}, fmt.Errorf("error while counting number of messages in mailbox %q: %w", mailToFind.Mailbox, err) } if count == 0 { return Mail{}, errEmptyMailbox } messages := make([]imap.Response, 0, count) messages, err = c.fetchMails(ctx, mailToFind.Mailbox) if err != nil { return Mail{}, fmt.Errorf("error while fetching messages in mailbox %q: %v", mailToFind.Mailbox, err) } for _, msg := range messages { mail, err := extract(ctx, msg) if err != nil { venom.Warn(ctx, "Cannot extract the content of the mail: %v", err) continue } // Handle the first found mail only found, err := mail.isSearched(mailToFind) if err != nil { return Mail{}, err } if found { return mail, nil } } return Mail{}, errMailNotFound } func (c *Client) fetchMails(ctx context.Context, mailbox string) ([]imap.Response, error) { venom.Debug(ctx, "Selecting mailbox %q", mailbox) if _, err := c.Select(mailbox, false); err != nil { venom.Error(ctx, "Error with select %s", err) return []imap.Response{}, err } seqset, _ := imap.NewSeqSet("1:*") messages := []imap.Response{} cmd, err := imap.Wait(c.Fetch(seqset, "UID", "ENVELOPE", "FLAGS", "RFC822.HEADER", "RFC822.TEXT", "BODY.PEEK[TEXT]")) if err != nil { venom.Error(ctx, "Error with FETCH command: %v", err) return []imap.Response{}, err } // Process command data for _, rsp := range cmd.Data { messages = append(messages, *rsp) } venom.Debug(ctx, "Fetched %d message(s) from mailbox %q", len(messages), mailbox) return messages, nil } func (c *Client) countNumberOfMessagesInMailbox(mailbox string) (uint32, error) { cmd, err := imap.Wait(c.Status(mailbox)) if err != nil { return 0, err } var count uint32 for _, result := range cmd.Data { mailboxStatus := result.MailboxStatus() if mailboxStatus != nil { count += mailboxStatus.Messages } } return count, nil } func (e Executor) connect(host, port, imapUsername, imapPassword string) (*imap.Client, error) { var ( err error c *imap.Client ) if e.Auth.WithTLS { c, err = imap.DialTLS(host+":"+port, &tls.Config{ InsecureSkipVerify: true, }) if err != nil { return nil, fmt.Errorf("unable to dialTLS: %s", err) } if c.Caps["STARTTLS"] { if _, err = imap.Wait(c.StartTLS(nil)); err != nil { return nil, fmt.Errorf("unable to start TLS: %s", err) } } } else { c, err = imap.Dial(host + ":" + port) if err != nil { return nil, fmt.Errorf("unable to dial: %s", err) } } c.SetLogMask(imapSafeLogMask) if _, err = imap.Wait(c.Login(imapUsername, imapPassword)); err != nil { return nil, fmt.Errorf("unable to login: %s", err) } c.SetLogMask(imapLogMask) return c, nil }
package request import "quan/model" type SysOperationRecordSearch struct { model.SysOperationRecord PageInfo }
package sudokuhistory import ( "errors" "github.com/jkomoros/sudoku" "github.com/jkomoros/sudoku/sdkconverter" "time" ) //Digest is an object representing the state of the model. Consists primarily //of a list of MoveGroupDigests. Suitable for being saved as json. type Digest struct { //Puzzle is the puzzle, encoded as a string in doku format. (See //sdkconverter package) Puzzle string MoveGroups []MoveGroupDigest } //MoveGroupDigest is the record of a group of moves that should all be applied //at once. Most MoveGroups have a single move, but some have multiple. type MoveGroupDigest struct { Moves []MoveDigest //How many nanoseconds elapsed since when the puzzle was reset to this //move. TimeOffset time.Duration `json:",omitempty"` //The description of the group (if it has one). Simple groups that contain //a single marks or number move often do not have group names. Description string `json:",omitempty"` } //MoveDigest is the record of a single move captured within a Digest, either //setting a number or setting a set of marks on a cell (but never both). type MoveDigest struct { Cell sudoku.CellRef //Which marks should be modified. Numbers that have a true should be set, //and numbers that have a false should be unset. All other marks will be //left the same. Either one or the other of Marks or Number may be set, //but never both. Marks map[int]bool `json:",omitempty"` //Which number to set. Either one or the other of Marks or Number may be //set, but never both. Number *int `json:",omitempty"` } //valid will return nil if it is valid, an error otherwise. func (d *Digest) valid() error { //Check that the puzzle exists. if d.Puzzle == "" { return errors.New("No puzzle") } //Check if the puzzle is a valid puzzle in doku format. converter := sdkconverter.Converters[sdkconverter.DokuFormat] if !converter.Valid(d.Puzzle) { return errors.New("Puzzle snapshot not doku format") } var lastTime time.Duration for _, group := range d.MoveGroups { if group.TimeOffset < 0 { return errors.New("Invalid time offset") } if group.TimeOffset < lastTime { return errors.New("TimeOffsets did not monotonically increase") } lastTime = group.TimeOffset if len(group.Moves) == 0 { return errors.New("One of the groups had no moves") } for _, move := range group.Moves { if move.Cell.Row < 0 || move.Cell.Row >= sudoku.DIM { return errors.New("Invalid row in cellref") } if move.Cell.Col < 0 || move.Cell.Col >= sudoku.DIM { return errors.New("Invalid col in cellref") } if move.Marks == nil && move.Number == nil { return errors.New("Neither marks nor number provided in move") } if move.Marks != nil && move.Number != nil { return errors.New("Both marks and number provided") } } } //Everything's OK! return nil } //LoadDigest takes in a Digest produced by model.Digest() and sets the //internal state appropriately. func (m *Model) LoadDigest(d Digest) error { if err := d.valid(); err != nil { return err } m.SetGrid(sdkconverter.Load(d.Puzzle)) for _, group := range d.MoveGroups { m.StartGroup(group.Description) for _, move := range group.Moves { if move.Marks != nil { m.SetMarks(move.Cell, move.Marks) } else { m.SetNumber(move.Cell, *move.Number) } } m.FinishGroupAndExecute() m.currentCommand.c.time = group.TimeOffset } return nil } //Digest returns a Digest object representing the state of this model. //Suitable for serializing as json. func (m *Model) Digest() Digest { return Digest{ Puzzle: m.snapshot, MoveGroups: m.makeMoveGroupsDigest(), } } func (m *Model) makeMoveGroupsDigest() []MoveGroupDigest { var result []MoveGroupDigest //Move command cursor to the very first item in the linked list. currentCommand := m.commands if currentCommand == nil { return nil } for currentCommand.prev != nil { currentCommand = currentCommand.prev } for currentCommand != nil { command := currentCommand.c var moves []MoveDigest for _, subCommand := range command.subCommands { moves = append(moves, MoveDigest{ //TODO: this is a hack, we just happen to know that there's only one item Cell: subCommand.ModifiedCells(m)[0], Marks: subCommand.Marks(), Number: subCommand.Number(), }) } result = append(result, MoveGroupDigest{ Moves: moves, Description: command.description, TimeOffset: command.time, }) currentCommand = currentCommand.next } return result }
package twitter import ( "crypto/hmac" "crypto/sha256" "encoding/base64" ) func (c *TwitterClient) CreateCRCToken(crcToken string) string { mac := hmac.New(sha256.New, []byte(c.envConfig.ConsumerSecret)) mac.Write([]byte(crcToken)) return "sha256=" + base64.StdEncoding.EncodeToString(mac.Sum(nil)) }
package cmd_test import ( "io/ioutil" "os" "path" "code.cloudfoundry.org/cfdev/cmd" "code.cloudfoundry.org/cfdev/config" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type MockUI struct { WasCalledWith string } func (m *MockUI) Say(message string, args ...interface{}) { m.WasCalledWith = message } var _ = Describe("Telemetry", func() { var ( tmpDir string mockUI MockUI conf config.Config analyticsFilePath string telCmd cmd.Telemetry ) BeforeEach(func() { mockUI = MockUI{ WasCalledWith: "", } tmpDir, _ = ioutil.TempDir(os.TempDir(), "testdir") conf = config.Config{ AnalyticsDir: path.Join(tmpDir, "analytics"), AnalyticsFile: "analytics-text.txt", } analyticsFilePath = path.Join(conf.AnalyticsDir, conf.AnalyticsFile) telCmd = cmd.Telemetry{ Config: conf, UI: &mockUI, } os.MkdirAll(conf.AnalyticsDir, 0755) }) AfterEach(func() { os.RemoveAll(tmpDir) }) Context("first arg", func() { It("ON", func() { ioutil.WriteFile(analyticsFilePath, []byte(""), 0755) telCmd.Run([]string{"oN"}) contents, err := ioutil.ReadFile(analyticsFilePath) Expect(err).NotTo(HaveOccurred()) Expect(string(contents[:])).To(Equal("optin")) Expect(mockUI.WasCalledWith).To(Equal("Telemetry is turned ON")) }) It("OFF", func() { ioutil.WriteFile(analyticsFilePath, []byte(""), 0755) telCmd.Run([]string{"oFf"}) contents, err := ioutil.ReadFile(analyticsFilePath) Expect(err).NotTo(HaveOccurred()) Expect(string(contents[:])).To(Equal("optout")) Expect(mockUI.WasCalledWith).To(Equal("Telemetry is turned OFF")) }) }) Context("No args displays status", func() { It("ON", func() { ioutil.WriteFile(analyticsFilePath, []byte("optin"), 0755) telCmd.Run([]string{}) Expect(mockUI.WasCalledWith).To(Equal("Telemetry is turned ON")) }) It("OFF", func() { ioutil.WriteFile(analyticsFilePath, []byte("optout"), 0755) telCmd.Run([]string{}) Expect(mockUI.WasCalledWith).To(Equal("Telemetry is turned OFF")) }) }) })
package vx /* #cgo CFLAGS: -std=c11 #cgo LDFLAGS: -lm #include <stdlib.h> */ import "C" import ( "math" "reflect" "unsafe" ) func AlignedAlloc(size int) []float32 { size_ := size size = align(size) ptr := C.aligned_alloc(32, (C.size_t)(C.sizeof_float*size)) hdr := reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(ptr)), Len: size, Cap: size, } goSlice := *(*[]float32)(unsafe.Pointer(&hdr)) if size_ != size { for i := size_; i < size; i++ { goSlice[i] = 0.0 } } return goSlice } func Free(v []float32) { C.free(unsafe.Pointer(&v[0])) } func align(size int) int { return int(math.Ceil(float64(size)/8.0) * 8.0) }
/* ================================================================================== Copyright (c) 2019 AT&T Intellectual Property. Copyright (c) 2019 Nokia Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================================================== */ package control /* #include <stdlib.h> #include <e2ap/wrapper.h> #cgo LDFLAGS: -le2apwrapper #cgo CFLAGS: -I/usr/local/include/e2ap */ import "C" import ( "errors" "unsafe" ) type E2ap struct { } /* RICsubscriptionRequest */ func (c *E2ap) GetSubscriptionRequestSequenceNumber(payload []byte) (subId uint16, err error) { cptr := unsafe.Pointer(&payload[0]) cret := C.e2ap_get_ric_subscription_request_sequence_number(cptr, C.size_t(len(payload))) if cret < 0 { return 0, errors.New("e2ap wrapper is unable to get Subscirption Request Sequence Number due to wrong or invalid payload") } subId = uint16(cret) return } func (c *E2ap) SetSubscriptionRequestSequenceNumber(payload []byte, newSubscriptionid uint16) (newPayload []byte, err error) { cptr := unsafe.Pointer(&payload[0]) size := C.e2ap_set_ric_subscription_request_sequence_number(cptr, C.size_t(len(payload)), C.long(newSubscriptionid)) if size < 0 { return make([]byte, 0), errors.New("e2ap wrapper is unable to set Subscription Request Sequence Number due to wrong or invalid payload") } newPayload = C.GoBytes(cptr, (C.int(size)+7)/8) return } func (c *E2ap) SetSubscriptionRequestPayload(payload []byte, ricRequestorID uint16, ricRequestSequenceNumber uint16, ranFunctionID uint16, eventTriggerDefinition []byte, eventTriggerDefinitionSize int, actionCount int, actionIds []int64, actionTypes []int64, actionDefinitions []ActionDefinition, subsequentActions []SubsequentAction) (newPayload []byte, err error) { cptr := unsafe.Pointer(&payload[0]) eventTrigger := unsafe.Pointer(&eventTriggerDefinition[0]) actIds := unsafe.Pointer(&actionIds[0]) actTypes := unsafe.Pointer(&actionTypes[0]) count := len(actionDefinitions) actDefs := (*C.RICactionDefinition)(C.calloc(C.size_t(len(actionDefinitions)), C.sizeof_RICactionDefinition)) for index := 0; index < count; index++ { ptr := *(*C.RICactionDefinition)(unsafe.Pointer((uintptr)(unsafe.Pointer(actDefs)) + (uintptr)(C.sizeof_RICactionDefinition*C.int(index)))) ptr.size = C.int(actionDefinitions[index].Size) if ptr.size != 0 { ptr.actionDefinition = (*C.uint8_t)(C.CBytes(actionDefinitions[index].Buf)) } } defer C.free(unsafe.Pointer(actDefs)) count = len(subsequentActions) subActs := (*C.RICSubsequentAction)(C.calloc(C.size_t(len(subsequentActions)), C.sizeof_RICSubsequentAction)) for index := 0; index < count; index++ { ptr := *(*C.RICSubsequentAction)(unsafe.Pointer((uintptr)(unsafe.Pointer(subActs)) + (uintptr)(C.sizeof_RICSubsequentAction*C.int(index)))) ptr.isValid = C.int(subsequentActions[index].IsValid) ptr.subsequentActionType = C.long(subsequentActions[index].SubsequentActionType) ptr.timeToWait = C.long(subsequentActions[index].TimeToWait) } defer C.free(unsafe.Pointer(subActs)) size := C.e2ap_encode_ric_subscription_request_message(cptr, C.size_t(len(payload)), C.long(ricRequestorID), C.long(ricRequestSequenceNumber), C.long(ranFunctionID), eventTrigger, C.size_t(eventTriggerDefinitionSize), C.int(actionCount), (*C.long)(actIds), (*C.long)(actTypes), actDefs, subActs) if size < 0 { return make([]byte, 0), errors.New("e2ap wrapper is unable to set Subscription Request Payload due to wrong or invalid payload") } newPayload = C.GoBytes(cptr, (C.int(size)+7)/8) return } /* RICsubscriptionResponse */ func (c *E2ap) GetSubscriptionResponseSequenceNumber(payload []byte) (subId uint16, err error) { cptr := unsafe.Pointer(&payload[0]) cret := C.e2ap_get_ric_subscription_response_sequence_number(cptr, C.size_t(len(payload))) if cret < 0 { return 0, errors.New("e2ap wrapper is unable to get Subscirption Response Sequence Number due to wrong or invalid payload") } subId = uint16(cret) return } func (c *E2ap) SetSubscriptionResponseSequenceNumber(payload []byte, newSubscriptionid uint16) (newPayload []byte, err error) { cptr := unsafe.Pointer(&payload[0]) size := C.e2ap_set_ric_subscription_response_sequence_number(cptr, C.size_t(len(payload)), C.long(newSubscriptionid)) if size < 0 { return make([]byte, 0), errors.New("e2ap wrapper is unable to set Subscription Response Sequence Number due to wrong or invalid payload") } newPayload = C.GoBytes(cptr, (C.int(size)+7)/8) return } func (c *E2ap) GetSubscriptionResponseMessage(payload []byte) (decodedMsg *DecodedSubscriptionResponseMessage, err error) { cptr := unsafe.Pointer(&payload[0]) decodedMsg = &DecodedSubscriptionResponseMessage{} decodedCMsg := C.e2ap_decode_ric_subscription_response_message(cptr, C.size_t(len(payload))) defer C.free(unsafe.Pointer(decodedCMsg)) if decodedCMsg == nil { return decodedMsg, errors.New("e2ap wrapper is unable to decode subscription response message due to wrong or invalid payload") } decodedMsg.RequestID = int32(decodedCMsg.requestorID) decodedMsg.RequestSequenceNumber = int32(decodedCMsg.requestSequenceNumber) decodedMsg.FuncID = int32(decodedCMsg.ranfunctionID) admittedCount := int(decodedCMsg.ricActionAdmittedList.count) for index := 0; index < admittedCount; index++ { decodedMsg.ActionAdmittedList.ActionID[index] = int32(decodedCMsg.ricActionAdmittedList.ricActionID[index]) } decodedMsg.ActionAdmittedList.Count = admittedCount notAdmittedCount := int(decodedCMsg.ricActionNotAdmittedList.count) for index := 0; index < notAdmittedCount; index++ { decodedMsg.ActionNotAdmittedList.ActionID[index] = int32(decodedCMsg.ricActionNotAdmittedList.ricActionID[index]) decodedMsg.ActionNotAdmittedList.Cause[index].CauseType = int32(decodedCMsg.ricActionNotAdmittedList.ricCause[index].ricCauseType) decodedMsg.ActionNotAdmittedList.Cause[index].CauseID = int32(decodedCMsg.ricActionNotAdmittedList.ricCause[index].ricCauseID) } decodedMsg.ActionNotAdmittedList.Count = notAdmittedCount return } /* RICsubscriptionFailure */ func (c *E2ap) GetSubscriptionFailureSequenceNumber(payload []byte) (subId uint16, err error) { cptr := unsafe.Pointer(&payload[0]) cret := C.e2ap_get_ric_subscription_failure_sequence_number(cptr, C.size_t(len(payload))) if cret < 0 { return 0, errors.New("e2ap wrapper is unable to get Subscirption Failure Sequence Number due to wrong or invalid payload") } subId = uint16(cret) return } /* RICsubscriptionDeleteRequest */ func (c *E2ap) GetSubscriptionDeleteRequestSequenceNumber(payload []byte) (subId uint16, err error) { cptr := unsafe.Pointer(&payload[0]) cret := C.e2ap_get_ric_subscription_delete_request_sequence_number(cptr, C.size_t(len(payload))) if cret < 0 { return 0, errors.New("e2ap wrapper is unable to get Subscirption Delete Request Sequence Number due to wrong or invalid payload") } subId = uint16(cret) return } func (c *E2ap) SetSubscriptionDeleteRequestSequenceNumber(payload []byte, newSubscriptionid uint16) (newPayload []byte, err error) { cptr := unsafe.Pointer(&payload[0]) size := C.e2ap_set_ric_subscription_delete_request_sequence_number(cptr, C.size_t(len(payload)), C.long(newSubscriptionid)) if size < 0 { return make([]byte, 0), errors.New("e2ap wrapper is unable to set Subscription Delete Request Sequence Number due to wrong or invalid payload") } newPayload = C.GoBytes(cptr, (C.int(size)+7)/8) return } func (c *E2ap) SetSubscriptionDeleteRequestPayload(payload []byte, ricRequestorID uint16, ricRequestSequenceNumber uint16, ranFunctionID uint16) (newPayload []byte, err error) { cptr := unsafe.Pointer(&payload[0]) size := C.e2ap_encode_ric_subscription_delete_request_message(cptr, C.size_t(len(payload)), C.long(ricRequestorID), C.long(ricRequestSequenceNumber), C.long(ranFunctionID)) if size < 0 { return make([]byte, 0), errors.New("e2ap wrapper is unable to set Subscription Delete Request Payload due to wrong or invalid payload") } newPayload = C.GoBytes(cptr, (C.int(size)+7)/8) return } /* RICsubscriptionDeleteResponse */ func (c *E2ap) GetSubscriptionDeleteResponseSequenceNumber(payload []byte) (subId uint16, err error) { cptr := unsafe.Pointer(&payload[0]) cret := C.e2ap_get_ric_subscription_delete_response_sequence_number(cptr, C.size_t(len(payload))) if cret < 0 { return 0, errors.New("e2ap wrapper is unable to get Subscirption Delete Response Sequence Number due to wrong or invalid payload") } subId = uint16(cret) return } func (c *E2ap) SetSubscriptionDeleteResponseSequenceNumber(payload []byte, newSubscriptionid uint16) (newPayload []byte, err error) { cptr := unsafe.Pointer(&payload[0]) size := C.e2ap_set_ric_subscription_delete_response_sequence_number(cptr, C.size_t(len(payload)), C.long(newSubscriptionid)) if size < 0 { return make([]byte, 0), errors.New("e2ap wrapper is unable to set Subscription Delete Response Sequence Number due to wrong or invalid payload") } newPayload = C.GoBytes(cptr, (C.int(size)+7)/8) return } /* RICsubscriptionDeleteFailure */ func (c *E2ap) GetSubscriptionDeleteFailureSequenceNumber(payload []byte) (subId uint16, err error) { cptr := unsafe.Pointer(&payload[0]) cret := C.e2ap_get_ric_subscription_delete_failure_sequence_number(cptr, C.size_t(len(payload))) if cret < 0 { return 0, errors.New("e2ap wrapper is unable to get Subscirption Failure Sequence Number due to wrong or invalid payload") } subId = uint16(cret) return } /* RICindication */ func (c *E2ap) GetIndicationMessage(payload []byte) (decodedMsg *DecodedIndicationMessage, err error) { cptr := unsafe.Pointer(&payload[0]) decodedMsg = &DecodedIndicationMessage{} decodedCMsg := C.e2ap_decode_ric_indication_message(cptr, C.size_t(len(payload))) if decodedCMsg == nil { return decodedMsg, errors.New("e2ap wrapper is unable to decode indication message due to wrong or invalid payload") } defer C.e2ap_free_decoded_ric_indication_message(decodedCMsg) decodedMsg.RequestID = int32(decodedCMsg.requestorID) decodedMsg.RequestSequenceNumber = int32(decodedCMsg.requestSequenceNumber) decodedMsg.FuncID = int32(decodedCMsg.ranfunctionID) decodedMsg.ActionID = int32(decodedCMsg.actionID) decodedMsg.IndSN = int32(decodedCMsg.indicationSN) decodedMsg.IndType = int32(decodedCMsg.indicationType) indhdr := unsafe.Pointer(decodedCMsg.indicationHeader) decodedMsg.IndHeader = C.GoBytes(indhdr, C.int(decodedCMsg.indicationHeaderSize)) decodedMsg.IndHeaderLength = int32(decodedCMsg.indicationHeaderSize) indmsg := unsafe.Pointer(decodedCMsg.indicationMessage) decodedMsg.IndMessage = C.GoBytes(indmsg, C.int(decodedCMsg.indicationMessageSize)) decodedMsg.IndMessageLength = int32(decodedCMsg.indicationMessageSize) callproc := unsafe.Pointer(decodedCMsg.callProcessID) decodedMsg.CallProcessID = C.GoBytes(callproc, C.int(decodedCMsg.callProcessIDSize)) decodedMsg.CallProcessIDLength = int32(decodedCMsg.callProcessIDSize) return }
package main import ( "bytes" "encoding/binary" "fmt" ) //整形转换成字节 func IntToBytes(n int) []byte { x := int32(n) bytesBuffer := bytes.NewBuffer([]byte{}) binary.Write(bytesBuffer, binary.BigEndian, x) return bytesBuffer.Bytes() } //字节转换成整形 func BytesToInt(b []byte) int { bytesBuffer := bytes.NewBuffer(b) var x int32 binary.Read(bytesBuffer, binary.BigEndian, &x) return int(x) } func main() { var a int a = 3 res := IntToBytes(a) b := BytesToInt(res) fmt.Println(res) fmt.Println(b) // var a uint32 // var b uint32 // rand.Seed(time.Now().UnixNano()) // a := rand.Intn(2) // b := rand.Intn(2) // c := a & b // a1, a2 := SecretCom(a) // b1, b2 := SecretCom(b) // c1, c2 := SecretCom(c) // fmt.Println(uint32(a1)) // fmt.Println(uint32(a2)) // fmt.Println(uint32(b1)) // fmt.Println(uint32(b2)) // fmt.Println(uint32(c1)) // fmt.Println(uint32(c2)) // v := uint32(500) //转换为无符号32位 // buf := make([]byte, 4) // //将 v 写入 buf中 // binary.BigEndian.PutUint32(buf, v) // //read // //从buf中读取并赋值给x // x := binary.BigEndian.Uint32(buf) // //res, err := GenerateRandomBytes(3) // fmt.Println("res", x) // var a int // p := &a // b := [10]int64{1} // s := "adsa" // bs := make([]byte, 10) // fmt.Println(binary.Size(a)) // -1 // fmt.Println(binary.Size(p)) // -1 // fmt.Println(binary.Size(b)) // 80 // fmt.Println(binary.Size(s)) // -1 // fmt.Println(binary.Size(bs)) // 10 //00000011 }
package classic // Merge two sorted linked lists and return it as a new list func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { var head, p, np *ListNode p1, p2 := l1, l2 for p1 != nil && p2 != nil { if p1.Val < p2.Val { np = p1 p1 = p1.Next } else { np = p2 p2 = p2.Next } if p == nil { head = np p = head } else { p.Next = np p = p.Next } } // add the rest to tail if p1 != nil { np = p1 } if p2 != nil { np = p2 } if p == nil { head = np } else { p.Next = np } return head }
package main import ( "log" "os" "phonebook_rest_api/config" "phonebook_rest_api/routes" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/joho/godotenv" ) func setupRoutes(app *fiber.App) { api := app.Group("/api") routes.ContactsRoute(api.Group("/contacts")) } func main() { if os.Getenv("APP_ENV") != "production" { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } } app := fiber.New() app.Use(cors.New()) app.Use(logger.New()) config.ConnectDB() setupRoutes(app) port := os.Getenv("PORT") err := app.Listen(":" + port) if err != nil { log.Fatal("Error app failed to start") panic(err) } }
package linter import ( "context" "testing" "github.com/suzuki/go-cmnt-eol-lint/src/env" ) func Test_Linter_LintFile(t *testing.T) { tests := map[string]struct { filename string expectedComments []string }{ "01_no_problem": { filename: "01_no_problem.go", expectedComments: []string{}, }, "02_ng": { filename: "02_ng.go", expectedComments: []string{ "Interface02 comment 1st line\nInterface02 comment 2nd line\n", "Struct02 is a structure for checking the comment eol\n", "Method is a method for checking the comment eol\n", "main02 is a main func for checking the comment eol\n", }, }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { path := getFixtureFilePath(tt.filename) ctx := context.Background() ctx = env.WithConfig(ctx) linter := New(env.GetConfig(ctx)) results, err := linter.LintFile(path) if err != nil { t.Fatalf("LintFile could not lint. path=%q err=%q", path, err) } if len(results) != len(tt.expectedComments) { t.Fatalf("Length of results is not match. want=%d got=%d", len(tt.expectedComments), len(results)) } for i, expectedComment := range tt.expectedComments { if results[i].Comment != expectedComment { t.Errorf("Comment is not match. want=%q got=%q", expectedComment, results[i].Comment) } } }) } } func getFixtureFilePath(filename string) string { return "../../fixture/" + filename }
package search import ( "testing" "math" "fmt" ) func TestSearch(t *testing.T) { x := []float64{0.1} direction := []float64{1} var eps float64 = 0.03 var min_y float64 test_cost_func := func(x []float64) (float64) { var y float64 y = math.Pow(x[0], 4) - 14 * math.Pow(x[0], 3) + 60 * math.Pow(x[0], 2) - 70 * x[0] fmt.Println(x[0], y) return y } fiSearch := newFiSearch(eps, test_cost_func) x[0] = fiSearch.search(x, direction) min_y = test_cost_func(x) fmt.Println(x[0], min_y) }
package pdns_api import ( "net/http" "github.com/jinzhu/gorm" "github.com/labstack/echo/v4" "github.com/pir5/pdns-api/model" ) // getRecords is getting records. // @Summary get records // @Description get records // @Security ID // @Security Secret // @Accept json // @Produce json // @Param id query int false "Record ID" // @Param domain_id query int false "Domain ID" // @Success 200 {array} model.Record // @Failure 404 {array} model.Record // @Failure 500 {object} pdns_api.HTTPError // @Router /records [get] // @Tags records func (h *recordHandler) getRecords(c echo.Context) error { whereParams := map[string]interface{}{} for k, v := range c.QueryParams() { if k != "id" && k != "domain_id" { return c.JSON(http.StatusForbidden, nil) } whereParams[k] = v } ds, err := h.recordModel.FindBy(whereParams) if err != nil { return c.JSON(http.StatusInternalServerError, err) } ids, err := filterDomains(ds.ToIntreface(), c) if err != nil { return c.JSON(http.StatusForbidden, err) } return c.JSON(http.StatusOK, ids) } // updateRecord is update record. // @Summary update record // @Description update record // @Security ID // @Security Secret // @Accept json // @Produce json // @Param id path integer true "Record ID " // @Param record body model.Record true "Record Object" // @Success 200 {object} model.Record // @Failure 403 {object} pdns_api.HTTPError // @Failure 404 {object} pdns_api.HTTPError // @Failure 500 {object} pdns_api.HTTPError // @Router /records/{id} [put] // @Tags records func (h *recordHandler) updateRecord(c echo.Context) error { if err := h.isAllowRecordID(c); err != nil { return err } nd := &model.Record{} if err := c.Bind(nd); err != nil { return c.JSON(http.StatusBadRequest, err) } updated, err := h.recordModel.UpdateByID(c.Param("id"), nd) if err != nil { return c.JSON(http.StatusInternalServerError, err) } if !updated { return c.JSON(http.StatusNotFound, "records does not exists") } return c.JSON(http.StatusOK, nil) } // enableRecord is enable record. // @Summary enable record // @Description enable record // @Security ID // @Security Secret // @Accept json // @Produce json // @Param id path integer true "Record ID " // @Param record body model.Record true "Record Object" // @Success 200 {object} model.Record // @Failure 403 {object} pdns_api.HTTPError // @Failure 404 {object} pdns_api.HTTPError // @Failure 500 {object} pdns_api.HTTPError // @Router /records/enable/{id} [put] // @Tags records func (h *recordHandler) enableRecord(c echo.Context) error { return changeState(h, c, false) } // disableRecord is disable record. // @Summary disable record // @Description disable record // @Security ID // @Security Secret // @Accept json // @Produce json // @Param id path integer true "Record ID " // @Param record body model.Record true "Record Object" // @Success 200 {object} model.Record // @Failure 403 {object} pdns_api.HTTPError // @Failure 404 {object} pdns_api.HTTPError // @Failure 500 {object} pdns_api.HTTPError // @Router /records/disable/{id} [put] // @Tags records func (h *recordHandler) disableRecord(c echo.Context) error { return changeState(h, c, true) } func changeState(h *recordHandler, c echo.Context, disabled bool) error { if err := h.isAllowRecordID(c); err != nil { return err } nd := &model.Record{ Disabled: &disabled, } updated, err := h.recordModel.UpdateByID(c.Param("id"), nd) if err != nil { return c.JSON(http.StatusInternalServerError, err) } if !updated { return c.JSON(http.StatusNotFound, "records does not exists") } return c.JSON(http.StatusOK, nil) } // deleteRecord is delete record. // @Summary delete record // @Description delete record // @Security ID // @Security Secret // @Accept json // @Produce json // @Param id path integer true "Record ID " // @Success 204 {object} model.Record // @Failure 403 {object} pdns_api.HTTPError // @Failure 404 {object} pdns_api.HTTPError // @Failure 500 {object} pdns_api.HTTPError // @Router /records/{id} [delete] // @Tags records func (h *recordHandler) deleteRecord(c echo.Context) error { err := h.isAllowRecordID(c) if err != nil { return err } deleted, err := h.recordModel.DeleteByID(c.Param("id")) if err != nil { return c.JSON(http.StatusInternalServerError, err) } if !deleted { return c.JSON(http.StatusNotFound, "records does not exists") } return c.NoContent(http.StatusNoContent) } // createRecord is create record. // @Summary create record // @Description create record // @Security ID // @Security Secret // @Accept json // @Produce json // @Param record body model.Record true "Record Object" // @Success 201 {object} model.Record // @Failure 403 {object} pdns_api.HTTPError // @Failure 404 {object} pdns_api.HTTPError // @Failure 500 {object} pdns_api.HTTPError // @Router /records [post] // @Tags records func (h *recordHandler) createRecord(c echo.Context) error { d := &model.Record{} if err := c.Bind(d); err != nil { return c.JSON(http.StatusBadRequest, err) } err := h.isAllowDomainID(c, d.DomainID) if err != nil { return err } if err := h.recordModel.Create(d); err != nil { return c.JSON(http.StatusInternalServerError, err) } return c.JSON(http.StatusCreated, d) } func (h *recordHandler) isAllowRecordID(c echo.Context) error { if !globalConfig.IsHTTPAuth() { return nil } ds, err := h.recordModel.FindBy(map[string]interface{}{ "id": []string{c.Param("id")}, }) if err != nil { return c.JSON(http.StatusInternalServerError, err) } if ds == nil || len(ds) == 0 { return c.JSON(http.StatusNotFound, "records does not exists") } return h.isAllowDomainID(c, ds[0].DomainID) } func (h *recordHandler) isAllowDomainID(c echo.Context, domainID int) error { if !globalConfig.IsHTTPAuth() { return nil } ds, err := h.domainModel.FindBy(map[string]interface{}{ "id": domainID, }) if err != nil { return c.JSON(http.StatusForbidden, nil) } if ds == nil || len(ds) == 0 { return c.JSON(http.StatusNotFound, "domains does not exists") } return isAllowDomain(c, ds[0].Name) } type recordHandler struct { recordModel model.RecordModeler domainModel model.DomainModeler } func NewRecordHandler(r model.RecordModeler, d model.DomainModeler) *recordHandler { return &recordHandler{ recordModel: r, domainModel: d, } } func RecordEndpoints(g *echo.Group, db *gorm.DB) { h := NewRecordHandler( model.NewRecordModeler(db), model.NewDomainModeler(db), ) g.GET("/records", h.getRecords) g.PUT("/records/:id", h.updateRecord) g.PUT("/records/enable/:id", h.enableRecord) g.PUT("/records/disable/:id", h.disableRecord) g.DELETE("/records/:id", h.deleteRecord) g.POST("/records", h.createRecord) }
package handlers import ( "fmt" "net/url" "strings" "github.com/authelia/authelia/v4/internal/duo" "github.com/authelia/authelia/v4/internal/middlewares" "github.com/authelia/authelia/v4/internal/model" "github.com/authelia/authelia/v4/internal/session" "github.com/authelia/authelia/v4/internal/utils" ) // DuoDevicesGET handler for retrieving available devices and capabilities from duo api. func DuoDevicesGET(duoAPI duo.API) middlewares.RequestHandler { return func(ctx *middlewares.AutheliaCtx) { var ( userSession session.UserSession err error ) if userSession, err = ctx.GetSession(); err != nil { ctx.Error(fmt.Errorf("failed to get session data: %w", err), messageMFAValidationFailed) return } values := url.Values{} values.Set("username", userSession.Username) ctx.Logger.Debugf("Starting Duo PreAuth for %s", userSession.Username) result, message, devices, enrollURL, err := DuoPreAuth(ctx, &userSession, duoAPI) if err != nil { ctx.Error(fmt.Errorf("duo PreAuth API errored: %w", err), messageMFAValidationFailed) return } if result == auth { if devices == nil { ctx.Logger.Debugf("No applicable device/method available for Duo user %s", userSession.Username) if err := ctx.SetJSONBody(DuoDevicesResponse{Result: enroll}); err != nil { ctx.Error(fmt.Errorf("unable to set JSON body in response"), messageMFAValidationFailed) } return } if err := ctx.SetJSONBody(DuoDevicesResponse{Result: auth, Devices: devices}); err != nil { ctx.Error(fmt.Errorf("unable to set JSON body in response"), messageMFAValidationFailed) } return } if result == allow { ctx.Logger.Debugf("Device selection not possible for user %s, because Duo authentication was bypassed - Defaults to Auto Push", userSession.Username) if err := ctx.SetJSONBody(DuoDevicesResponse{Result: allow}); err != nil { ctx.Error(fmt.Errorf("unable to set JSON body in response"), messageMFAValidationFailed) } return } if result == enroll { ctx.Logger.Debugf("Duo user: %s not enrolled", userSession.Username) if err := ctx.SetJSONBody(DuoDevicesResponse{Result: enroll, EnrollURL: enrollURL}); err != nil { ctx.Error(fmt.Errorf("unable to set JSON body in response"), messageMFAValidationFailed) } return } if result == deny { ctx.Logger.Debugf("Duo User not allowed to authenticate: %s", userSession.Username) if err := ctx.SetJSONBody(DuoDevicesResponse{Result: deny}); err != nil { ctx.Error(fmt.Errorf("unable to set JSON body in response"), messageMFAValidationFailed) } return } ctx.Error(fmt.Errorf("duo PreAuth API errored for %s: %s - %s", userSession.Username, result, message), messageMFAValidationFailed) } } // DuoDevicePOST update the user preferences regarding Duo device and method. func DuoDevicePOST(ctx *middlewares.AutheliaCtx) { bodyJSON := DuoDeviceBody{} var ( userSession session.UserSession err error ) if err = ctx.ParseBody(&bodyJSON); err != nil { ctx.Error(err, messageMFAValidationFailed) return } if !utils.IsStringInSlice(bodyJSON.Method, duo.PossibleMethods) { ctx.Error(fmt.Errorf("unknown method '%s', it should be one of %s", bodyJSON.Method, strings.Join(duo.PossibleMethods, ", ")), messageMFAValidationFailed) return } if userSession, err = ctx.GetSession(); err != nil { ctx.Error(err, messageMFAValidationFailed) return } ctx.Logger.Debugf("Save new preferred Duo device and method of user %s to %s using %s", userSession.Username, bodyJSON.Device, bodyJSON.Method) err = ctx.Providers.StorageProvider.SavePreferredDuoDevice(ctx, model.DuoDevice{Username: userSession.Username, Device: bodyJSON.Device, Method: bodyJSON.Method}) if err != nil { ctx.Error(fmt.Errorf("unable to save new preferred Duo device and method: %w", err), messageMFAValidationFailed) return } ctx.ReplyOK() } // DuoDeviceDELETE deletes the useres preferred Duo device and method. func DuoDeviceDELETE(ctx *middlewares.AutheliaCtx) { var ( userSession session.UserSession err error ) if userSession, err = ctx.GetSession(); err != nil { ctx.Error(fmt.Errorf("unable to get session to delete preferred Duo device and method: %w", err), messageMFAValidationFailed) return } ctx.Logger.Debugf("Deleting preferred Duo device and method of user %s", userSession.Username) if err = ctx.Providers.StorageProvider.DeletePreferredDuoDevice(ctx, userSession.Username); err != nil { ctx.Error(fmt.Errorf("unable to delete preferred Duo device and method: %w", err), messageMFAValidationFailed) return } ctx.ReplyOK() }
package controllers import ( "sdrms/models" "encoding/json" ) type SystemLoginLogController struct { BaseController } func (c *SystemLoginLogController) Prepare() { //先执行 c.BaseController.Prepare() //如果一个Controller的多数Action都需要权限控制,则将验证放到Prepare c.checkAuthor("DataGrid") //如果一个Controller的所有Action都需要登录验证,则将验证放到Prepare //权限控制里会进行登录验证,因此这里不用再作登录验证 //c.checkLogin() } // @router / [get] func (c *SystemLoginLogController) Index() { //是否显示更多查询条件的按钮 c.Data["showMoreQuery"] = true //将页面左边菜单的某项激活 c.Data["activeSidebarUrl"] = c.URLFor(c.controllerName + "." + c.actionName) //页面模板设置 c.setTpl() c.LayoutSections = make(map[string]string) c.LayoutSections["headcssjs"] = "systemloginlog/index_headcssjs.html" c.LayoutSections["footerjs"] = "systemloginlog/index_footerjs.html" //c.Data["canDelete"] = c.checkActionAuthor("SystemLoginLogController", "Delete") } // @router /DataGrid [post] func (c *SystemLoginLogController) DataGrid() { //直接反序化获取json格式的requestbody里的值(要求配置文件里 copyrequestbody=true) var params models.SystemLoginLogQueryParam json.Unmarshal(c.Ctx.Input.RequestBody, &params) //获取数据列表和总数 data, total := models.SystemLoginLogPageList(&params) //定义返回的数据结构 result := make(map[string]interface{}) result["total"] = total result["rows"] = data c.Data["json"] = result c.ServeJSON() }
package server import ( "encoding/json" "fmt" "net/http" "net/url" colly "github.com/gocolly/colly/v2" "github.com/guschnwg/player/pkg/shared" ) const baseURL = "https://www.beatport.com" // TestBeatport ... func TestBeatport(w http.ResponseWriter, r *http.Request) { enableCors(&w, r) query := r.URL.Query().Get("query") if query == "" { query = "Eats Everything - Space Raiders (Charlotte de Witte Remix)" } c := colly.NewCollector(colly.MaxDepth(1)) data := shared.BeatportData{} visited := false c.OnHTML(".bucket-items > .bucket-item:first-child > .buk-track-meta-parent > .buk-track-title > a", func(e *colly.HTMLElement) { if !visited { visited = true c.Visit(baseURL + e.Attr("href")) } }) c.OnHTML(".interior-track-content-list > .interior-track-genre > .value > a", func(e *colly.HTMLElement) { fmt.Println("FOUND " + e.Text) data.Genre = e.Text }) c.OnHTML(".interior-track-content-list > .interior-track-bpm > .value", func(e *colly.HTMLElement) { fmt.Println("FOUND " + e.Text) data.BPM = e.Text }) err := c.Visit(baseURL + "/search?q=" + url.QueryEscape(query)) if err != nil { w.WriteHeader(500) json.NewEncoder(w).Encode(map[string]interface{}{ "error": err.Error(), }) return } json.NewEncoder(w).Encode(map[string]interface{}{ "results": data, }) }
package types import "encoding/json" type Result struct { Result []json.RawMessage `json:"result"` Count int `json:"count"` Cached bool `json:"cached"` HasMore bool `json:"hasMore"` Error bool `json:"error"` Code int `json:"code"` } type Results struct { Result json.RawMessage `json:"result"` Count int `json:"count"` Cached bool `json:"cached"` HasMore bool `json:"hasMore"` Error bool `json:"error"` Code int `json:"code"` }
package stage import "github.com/werf/werf/pkg/config" func GenerateImportsAfterSetupStage(imageBaseConfig *config.StapelImageBase, baseStageOptions *NewBaseStageOptions) *ImportsAfterSetupStage { imports := getImports(imageBaseConfig, &getImportsOptions{After: Setup}) if len(imports) != 0 { return newImportsAfterSetupStage(imports, baseStageOptions) } return nil } func newImportsAfterSetupStage(imports []*config.Import, baseStageOptions *NewBaseStageOptions) *ImportsAfterSetupStage { s := &ImportsAfterSetupStage{} s.ImportsStage = newImportsStage(imports, ImportsAfterSetup, baseStageOptions) return s } type ImportsAfterSetupStage struct { *ImportsStage }
package logs import ( "github.com/profiralex/go-bootstrap-redis/pkg/config" log "github.com/sirupsen/logrus" ) func Init(cfg config.Config) { debugLevel, err := log.ParseLevel(cfg.AppConfig.DebugLevel) if err != nil { log.Warnf("Unknown debug level %s defaulting to warning level", cfg.AppConfig.DebugLevel) debugLevel = log.WarnLevel } log.SetLevel(debugLevel) log.SetFormatter(&log.JSONFormatter{}) log.SetReportCaller(true) }
package user import "errors" type UserId struct { value string } func NewUserId(value string) (*UserId, error) { for _, v := range []bool{ len(value) < 4, len(value) > 32, } { if v { return nil, errors.New("assertion error") } } return &UserId{value}, nil } func (u *UserId) Value() string { return u.value }
package main func distributeCandies(candies []int) int { candyKinds := 0 candyCount := make(map[int]int) for i := 0; i < len(candies); i++ { candyCount[candies[i]]++ if candyCount[candies[i]] == 1 { candyKinds++ } } if candyKinds > len(candies)>>1 { candyKinds = len(candies) >> 1 } return candyKinds } /* 贪心策略: 让妹妹每一种糖果只拿一个,这样可以保证妹妹糖果的种类最多。 又为了妹妹和弟弟的糖果均分,假如妹妹手中的糖果大于 总糖果数/2,那就要把妹妹超出的糖果分给弟弟。 */ /* 题目链接: https://leetcode-cn.com/problems/distribute-candies/solution/tong-guo-bi-jiao-tang-guo-chong-lei-shu-liang-he-t/ 分糖果 */ /* 总结 1. 这题目还可以使用排序,排序后获得糖果的种类,这样可以使空间复杂度降为O(1),但是时间复杂度会升为O(nlogn) */
package main import ( "fmt" "github.com/stretchr/testify/require" "log" "strings" "testing" "time" ) func Test_Nas_Error(t *testing.T) { runOnlyInIntegrationTest("TEST_CLOUDFERRO") ferroTearDown() defer ferroTearDown() brokerd_launched, err := isBrokerdLaunched() if !brokerd_launched { fmt.Println("This requires that you launch brokerd in background and set the tenant") require.True(t, brokerd_launched) } require.Nil(t, err) in_path, err := canBeRun("broker") require.Nil(t, err) require.True(t, brokerd_launched) require.True(t, in_path) out, err := getOutput("broker tenant list") require.Nil(t, err) require.True(t, len(out) > 0) out, err = getOutput("broker tenant get") if err != nil { fmt.Println("This requires that you set the right tenant before launching the tests") require.Nil(t, err) } require.True(t, len(out) > 0) out, err = getOutput("broker network list") require.Nil(t, err) fmt.Println("Creating network ferronet...") out, err = getOutput("broker network create ferronet") require.Nil(t, err) fmt.Println("Creating VM ferrohost...") out, err = getOutput("broker host create ferrohost --public --net ferronet") require.Nil(t, err) out, err = getOutput("broker host inspect ferrohost") require.Nil(t, err) fmt.Println("Creating Nas ferronas...") out, err = getOutput("broker nas create ferronas ferrohost") require.Nil(t, err) fmt.Println("Creating Volume volumetest...") out, err = getOutput("broker volume create --speed SSD volumetest") require.Nil(t, err) out, err = getOutput("broker volume list") require.Nil(t, err) require.True(t, strings.Contains(out, "volumetest")) out, err = getOutput("broker volume attach volumetest ferrohost") require.Nil(t, err) time.Sleep(5 * time.Second) out, err = getOutput("broker volume delete volumetest") require.NotNil(t, err) require.True(t, strings.Contains(out, "still attached")) time.Sleep(5 * time.Second) out, err = getOutput("broker volume detach volumetest ferrohost") require.Nil(t, err) time.Sleep(5 * time.Second) out, err = getOutput("broker volume delete volumetest") require.Nil(t, err) time.Sleep(5 * time.Second) out, err = getOutput("broker volume list") require.Nil(t, err) require.True(t, strings.Contains(out, "null")) out, err = getOutput("broker ssh run ferrohost -c \"uptime\"") require.Nil(t, err) require.True(t, strings.Contains(out, "0 users")) out, err = getOutput("broker nas delete ferronas ") require.Nil(t, err) out, err = getOutput("broker host delete ferrohost") if err != nil { fmt.Println(err.Error()) fmt.Println(out) } require.Nil(t, err) require.True(t, strings.Contains(out, "deleted")) out, err = getOutput("broker network delete ferronet") require.Nil(t, err) require.True(t, strings.Contains(out, "deleted")) } func Test_Until_Volume_Error(t *testing.T) { runOnlyInIntegrationTest("TEST_CLOUDFERRO") ferroTearDown() // defer ferroTearDown() brokerd_launched, err := isBrokerdLaunched() if !brokerd_launched { fmt.Println("This requires that you launch brokerd in background and set the tenant") require.True(t, brokerd_launched) } require.Nil(t, err) in_path, err := canBeRun("broker") require.Nil(t, err) require.True(t, brokerd_launched) require.True(t, in_path) out, err := getOutput("broker tenant list") require.Nil(t, err) require.True(t, len(out) > 0) out, err = getOutput("broker tenant get") if err != nil { fmt.Println("This requires that you set the right tenant before launching the tests") require.Nil(t, err) } require.True(t, len(out) > 0) out, err = getOutput("broker network list") require.Nil(t, err) fmt.Println("Creating network ferronet...") out, err = getOutput("broker network create ferronet") require.Nil(t, err) fmt.Println("Creating VM ferrohost...") out, err = getOutput("broker host create ferrohost --public --net ferronet") require.Nil(t, err) out, err = getOutput("broker host inspect ferrohost") require.Nil(t, err) fmt.Println("Creating Nas ferronas...") out, err = getOutput("broker nas create ferronas ferrohost") require.Nil(t, err) fmt.Println("Creating Volume volumetest...") out, err = getOutput("broker volume create volumetest") require.Nil(t, err) time.Sleep(5 * time.Second) out, err = getOutput("broker volume attach volumetest ferrohost") require.Nil(t, err) time.Sleep(5 * time.Second) out, err = getOutput("broker volume delete volumetest") require.NotNil(t, err) require.True(t, strings.Contains(out, "still attached")) } func Test_Ready_To_Ssh(t *testing.T) { runOnlyInIntegrationTest("TEST_CLOUDFERRO") ferroTearDown() brokerd_launched, err := isBrokerdLaunched() if !brokerd_launched { fmt.Println("This requires that you launch brokerd in background and set the tenant") require.True(t, brokerd_launched) } require.Nil(t, err) in_path, err := canBeRun("broker") require.Nil(t, err) require.True(t, brokerd_launched) require.True(t, in_path) out, err := getOutput("broker tenant list") require.Nil(t, err) require.True(t, len(out) > 0) out, err = getOutput("broker tenant get") if err != nil { fmt.Println("This requires that you set the right tenant before launching the tests") require.Nil(t, err) } require.True(t, len(out) > 0) out, err = getOutput("broker network list") require.Nil(t, err) fmt.Println("Creating network ferronet...") out, err = getOutput("broker network create ferronet") require.Nil(t, err) fmt.Println("Creating VM ferrohost...") out, err = getOutput("broker host create ferrohost --public --net ferronet") require.Nil(t, err) out, err = getOutput("broker host inspect ferrohost") require.Nil(t, err) fmt.Println(out) } func Test_Nas_Cleanup(t *testing.T) { runOnlyInIntegrationTest("TEST_CLOUDFERRO") ferroTearDown() } func ferroTearDown() { runOnlyInIntegrationTest("TEST_CLOUDFERRO") log.Printf("Starting cleanup...") _, _ = getOutput("broker nas delete ferronas") time.Sleep(5 * time.Second) _, _ = getOutput("broker volume detach volumetest ferrohost") time.Sleep(5 * time.Second) _, _ = getOutput("broker volume delete volumetest") time.Sleep(5 * time.Second) _, _ = getOutput("broker host delete ferrohost") time.Sleep(5 * time.Second) _, _ = getOutput("broker network delete ferronet") time.Sleep(5 * time.Second) log.Printf("Finishing cleanup...") }
package main import ( "fmt" "time" ) func main() { var ch = make(chan bool) go func() { select { case <-ch: fmt.Println("2 ") } }() fmt.Println("1 ") time.Sleep(2 * time.Second) ch <- true fmt.Println("3 ") }
package main type config struct { ip string port int }
/* * @lc app=leetcode.cn id=18 lang=golang * * [18] 四数之和 */ // @lc code=start package main import ( "fmt" "sort" ) func fourSum(nums []int, target int) [][]int { sort.Ints(nums) n := len(nums) res := [][]int{} for first := 0 ; first < n - 3 ; first++ { if first > 0 && nums[first] == nums[first-1] { continue } for second := first + 1 ; second < n - 2 ; second++{ if second > first + 1 && nums[second] == nums[second - 1] { continue } for third := second + 1 ; third < n -1 ; third++ { if third > second + 1 && nums[third] == nums[third - 1] { continue } left := target - nums[first] - nums[second] - nums[third] fourth := n - 1 for nums[fourth] > left && fourth > third { fourth-- } if fourth == third { continue } if nums[fourth] + nums[first] + nums[second] + nums[third] == target { res = append(res, []int{nums[first],nums[second], nums[third], nums[fourth]}) } } } } return res } // @lc code=end func main() { a := []int{1, 0, -1, 0, -2, 2} fmt.Printf("original are %v, res is %v\n", a, fourSum(a, 0 )) b := []int{3,0,-2,-1,1,2} fmt.Printf("original are %v, res is %v\n", b, fourSum(b, 0)) c := []int{-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0} fmt.Printf("original are %v, res is %v\n", c, fourSum(c, 0)) }
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03400108 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.034.001.08 Document"` Message *CorporateActionInstructionStatusAdviceV08 `xml:"CorpActnInstrStsAdvc"` } func (d *Document03400108) AddMessage() *CorporateActionInstructionStatusAdviceV08 { d.Message = new(CorporateActionInstructionStatusAdviceV08) return d.Message } // Scope // An account servicer sends the CorporateActionInstructionStatusAdvice message to an account owner or its designated agent, to report status of a received corporate action election instruction. // This message is used to advise the status, or a change in status, of a corporate action-related transaction previously instructed by, or executed on behalf of, the account owner. This will include the acknowledgement/rejection of a corporate action instruction. // Usage // The message may also be used to: // - re-send a message previously sent (the sub-function of the message is Duplicate), // - provide a third party with a copy of a message for information (the sub-function of the message is Copy), // - re-send to a third party a copy of a message for information (the sub-function of the message is Copy Duplicate), // using the relevant elements in the business application header (BAH). type CorporateActionInstructionStatusAdviceV08 struct { // Identification of a related instruction document. InstructionIdentification *iso20022.DocumentIdentification9 `xml:"InstrId,omitempty"` // Identification of other documents as well as the document number. OtherDocumentIdentification []*iso20022.DocumentIdentification33 `xml:"OthrDocId,omitempty"` // General information about the corporate action event. CorporateActionGeneralInformation *iso20022.CorporateActionGeneralInformation109 `xml:"CorpActnGnlInf"` // Provides information about the processing status of the instruction. InstructionProcessingStatus []*iso20022.InstructionProcessingStatus29Choice `xml:"InstrPrcgSts"` // Information about the corporate action instruction. CorporateActionInstruction *iso20022.CorporateActionOption116 `xml:"CorpActnInstr,omitempty"` // Provides additional information. AdditionalInformation *iso20022.CorporateActionNarrative10 `xml:"AddtlInf,omitempty"` // Additional information that can not be captured in the structured fields and/or any other specific block. SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (c *CorporateActionInstructionStatusAdviceV08) AddInstructionIdentification() *iso20022.DocumentIdentification9 { c.InstructionIdentification = new(iso20022.DocumentIdentification9) return c.InstructionIdentification } func (c *CorporateActionInstructionStatusAdviceV08) AddOtherDocumentIdentification() *iso20022.DocumentIdentification33 { newValue := new(iso20022.DocumentIdentification33) c.OtherDocumentIdentification = append(c.OtherDocumentIdentification, newValue) return newValue } func (c *CorporateActionInstructionStatusAdviceV08) AddCorporateActionGeneralInformation() *iso20022.CorporateActionGeneralInformation109 { c.CorporateActionGeneralInformation = new(iso20022.CorporateActionGeneralInformation109) return c.CorporateActionGeneralInformation } func (c *CorporateActionInstructionStatusAdviceV08) AddInstructionProcessingStatus() *iso20022.InstructionProcessingStatus29Choice { newValue := new(iso20022.InstructionProcessingStatus29Choice) c.InstructionProcessingStatus = append(c.InstructionProcessingStatus, newValue) return newValue } func (c *CorporateActionInstructionStatusAdviceV08) AddCorporateActionInstruction() *iso20022.CorporateActionOption116 { c.CorporateActionInstruction = new(iso20022.CorporateActionOption116) return c.CorporateActionInstruction } func (c *CorporateActionInstructionStatusAdviceV08) AddAdditionalInformation() *iso20022.CorporateActionNarrative10 { c.AdditionalInformation = new(iso20022.CorporateActionNarrative10) return c.AdditionalInformation } func (c *CorporateActionInstructionStatusAdviceV08) AddSupplementaryData() *iso20022.SupplementaryData1 { newValue := new(iso20022.SupplementaryData1) c.SupplementaryData = append(c.SupplementaryData, newValue) return newValue }
package problem0476 func findComplement(num int) int { mask := 1 << 30 for (num & mask) == 0 { mask >>= 1 } mask = mask<<1 - 1 return num ^ mask }
package main import "fmt" func main() { fmt.Println("f1") fmt.Println("f2") fmt.Println("f3") goto f6 fmt.Println("f4") fmt.Println("f5") f6: fmt.Println("f6") // loop: // for i := 0; i < 10; i++ { // fmt.Println(i) // if i == 2 { // goto loop // 这种直接goto到for循环 相当于重新开始循环 i :=0,而不像cotinue一样会从迭代循环变量i++开始 // } // } } //跳转控制语句goto // 1)Go语言的goto语句可以无条件地转移到程序中指定的行 // 2)goto语句通常与条件语句配合使用,可用来实现条件的转移跳出循环体等功能 // 3)在Go程序设计中一般不主张使用goto语句,以免照成程序流程的混乱,使理解和调试程序都困难
package coinswap import ( "fmt" "time" sdk "github.com/irisnet/irishub/types" ) // NewHandler returns a handler for "coinswap" type messages. func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { case MsgSwapOrder: return HandleMsgSwapOrder(ctx, msg, k) case MsgAddLiquidity: return HandleMsgAddLiquidity(ctx, msg, k) case MsgRemoveLiquidity: return HandleMsgRemoveLiquidity(ctx, msg, k) default: errMsg := fmt.Sprintf("unrecognized coinswap message type: %T", msg) return sdk.ErrUnknownRequest(errMsg).Result() } } } // Handle MsgSwapOrder. func HandleMsgSwapOrder(ctx sdk.Context, msg MsgSwapOrder, k Keeper) sdk.Result { // check that deadline has not passed if ctx.BlockHeader().Time.After(time.Unix(msg.Deadline, 0)) { return ErrInvalidDeadline("deadline has passed for MsgSwapOrder").Result() } tags, err := k.HandleSwap(ctx, msg) if err != nil { return err.Result() } return sdk.Result{Tags: tags} } // Handle MsgAddLiquidity. If the reserve pool does not exist, it will be // created. The first liquidity provider sets the exchange rate. func HandleMsgAddLiquidity(ctx sdk.Context, msg MsgAddLiquidity, k Keeper) sdk.Result { // check that deadline has not passed if ctx.BlockHeader().Time.After(time.Unix(msg.Deadline, 0)) { return ErrInvalidDeadline("deadline has passed for MsgAddLiquidity").Result() } tags, err := k.HandleAddLiquidity(ctx, msg) if err != nil { return err.Result() } return sdk.Result{ Tags: tags, } } // HandleMsgRemoveLiquidity handler for MsgRemoveLiquidity func HandleMsgRemoveLiquidity(ctx sdk.Context, msg MsgRemoveLiquidity, k Keeper) sdk.Result { // check that deadline has not passed if ctx.BlockHeader().Time.After(time.Unix(msg.Deadline, 0)) { return ErrInvalidDeadline("deadline has passed for MsgRemoveLiquidity").Result() } tags, err := k.HandleRemoveLiquidity(ctx, msg) if err != nil { return err.Result() } return sdk.Result{ Tags: tags, } }
package main import ( "encoding/json" "fmt" "html/template" "log" "net/http" "sort" "github.com/luno/moonbeam/resolver" "github.com/luno/moonbeam/storage" ) func render(t *template.Template, w http.ResponseWriter, data interface{}) { if err := t.Execute(w, data); err != nil { log.Printf("template error: %v", err) http.Error(w, "template error", http.StatusInternalServerError) return } } const header = `<!DOCTYPE html> <html> <head> <title>Moonbeam</title> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> </style> </head> <body> <div class="container">` const footer = ` </div> </body> </html>` var indexT = template.Must(template.New("index").Parse(header + ` <h1>Moonbeam</h1> <p>Moonbeam is a protocol that uses Bitcoin payment channels to facilitate instant off-chain payments between multi-user platforms.</p> <p>This is a demo server running on testnet.</p> <h4>More info</h4> <ul> <li><a href="https://github.com/luno/moonbeam">Github</a></li> <li><a href="https://github.com/luno/moonbeam/blob/master/docs/overview.md">Overview</a></li> <li><a href="https://github.com/luno/moonbeam/blob/master/docs/quickstart.md">Quickstart</a></li> <li><a href="https://github.com/luno/moonbeam/blob/master/docs/spec.md">Specification</a></li> </ul> <h4>Channels</h4> <table class="table"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Capacity</th> <th>Balance</th> <th>Count</th> </tr> </thead> <tbody> {{range .ChanItems}} <tr> <td><a href="/details?id={{.ID}}">{{.ID}}</a></td> <td>{{.SharedState.Status}}</td> <td>{{.SharedState.Capacity}}</td> <td>{{.SharedState.Balance}}</td> <td>{{.SharedState.Count}}</td> </tr> {{end}} </tbody> </table> ` + footer)) func indexHandler(ss *ServerState, w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } recs, err := ss.Receiver.List() if err != nil { http.Error(w, "error", http.StatusInternalServerError) return } sort.Sort(chanItems(recs)) c := struct { ChanItems []storage.Record }{recs} render(indexT, w, c) } type chanItems []storage.Record func (items chanItems) Len() int { return len(items) } func (items chanItems) Less(i, j int) bool { return items[i].ID > items[j].ID } func (items chanItems) Swap(i, j int) { items[i], items[j] = items[j], items[i] } var detailsT = template.Must(template.New("index").Parse(header + ` <h1>Channel details</h1> <p><a href="/">Home</a></p> <p>ID: {{.ID}}</p> <pre>{{.StateJSON}}</pre> <h2>Payments</h2> {{if .Payments}} <table> {{range .Payments}} <tr><td><code>{{.}}</code></td></tr> {{end}} </table> {{else}} None {{end}} ` + footer)) func detailsHandler(ss *ServerState, w http.ResponseWriter, r *http.Request) { txid, vout, ok := splitTxIDVout(r.FormValue("id")) if !ok { http.NotFound(w, r) return } s := ss.Receiver.Get(txid, vout) if s == nil { http.NotFound(w, r) return } payments, err := ss.Receiver.ListPayments(txid, vout) if err != nil { log.Printf("error: %v", err) http.Error(w, "error", http.StatusInternalServerError) return } var pl []string for _, p := range payments { pl = append(pl, string(p)) } buf, err := json.MarshalIndent(s, "", " ") if err != nil { http.Error(w, "error", http.StatusInternalServerError) return } c := struct { ID string StateJSON string Payments []string }{fmt.Sprintf("%s-%d", txid, vout), string(buf), pl} render(detailsT, w, c) } func domainHandler(w http.ResponseWriter, r *http.Request) { d := resolver.Domain{ Receivers: []resolver.DomainReceiver{ {URL: *externalURL + rpcPath}, }, } json.NewEncoder(w).Encode(d) }
package _interface import ( "fmt" "testing" "time" ) type Programmer interface { WriteHelloWorld() string } type GoProgrammer struct { } func (g *GoProgrammer) WriteHelloWorld() string { return "fmt.Println(\"Hello World\")" } func TestClient(t *testing.T) { var p Programmer p = new(GoProgrammer) t.Log(p.WriteHelloWorld()) } type IntConv func(oop int) int func timeSpent(inner IntConv) IntConv{ return func(n int) int { start := time.Now() ret := inner(n) fmt.Println("time spent: ", time.Since(start).Seconds()) return ret } } func slowFun(ops int) int { time.Sleep(time.Second * 1) fmt.Println("hello slow fun") return ops } func TestFun(t *testing.T) { tsSF := timeSpent(slowFun) t.Log(tsSF(10)) }
package riak import ( "errors" "github.com/cupcake/go-riak/pb" ) // A Riak link type Link struct { Bucket string Key string Tag string } // An object van have siblings that can each have their own content type Sibling struct { ContentType string Data []byte Links []Link Meta map[string]string Indexes map[string]string } // An RObject is an object or document that is or can be stored in Riak type RObject struct { Bucket *Bucket Vclock []byte Key string ContentType string Data []byte Links []Link Meta map[string]string Indexes map[string]string conflict bool Siblings []Sibling Options []map[string]uint32 } // Error definitions var ( NotFound = errors.New("Object not found") ) // Store an RObject func (obj *RObject) Store() (err error) { // Create base pb.RpbPutReq t := true req := &pb.RpbPutReq{ Bucket: []byte(obj.Bucket.name), Content: &pb.RpbContent{ Value: []byte(obj.Data), ContentType: []byte(obj.ContentType), }, ReturnHead: &t, } if obj.Key != "" { req.Key = []byte(obj.Key) } if len(obj.Vclock) > 0 { req.Vclock = obj.Vclock } // Add the links req.Content.Links = make([]*pb.RpbLink, len(obj.Links)) for i, v := range obj.Links { req.Content.Links[i] = &pb.RpbLink{Bucket: []byte(v.Bucket), Key: []byte(v.Key), Tag: []byte(v.Tag)} } // Add the user metadata req.Content.Usermeta = make([]*pb.RpbPair, len(obj.Meta)) i := 0 for k, v := range obj.Meta { req.Content.Usermeta[i] = &pb.RpbPair{Key: []byte(k), Value: []byte(v)} i += 1 } // Add the indexes req.Content.Indexes = make([]*pb.RpbPair, len(obj.Indexes)) i = 0 for k, v := range obj.Indexes { req.Content.Indexes[i] = &pb.RpbPair{Key: []byte(k), Value: []byte(v)} i += 1 } // Add the options for _, omap := range obj.Options { for k, v := range omap { switch k { case "w": req.W = &v case "dw": req.Dw = &v case "pw": req.Pw = &v } } } // Send the request err, conn := obj.Bucket.client.request(req, rpbPutReq) if err != nil { return err } // Get response, ReturnHead is true, so we can store the vclock resp := &pb.RpbPutResp{} err = obj.Bucket.client.response(conn, resp) if err != nil { return err } obj.Vclock = resp.Vclock // If applicable, store the key if obj.Key == "" { obj.Key = string(resp.Key) } return nil } // Delete the object from Riak func (obj *RObject) Destroy() (err error) { req := &pb.RpbDelReq{Bucket: []byte(obj.Bucket.name), Key: []byte(obj.Key), Vclock: obj.Vclock} for _, omap := range obj.Options { for k, v := range omap { switch k { case "r": req.R = &v case "pr": req.Pr = &v case "rq": req.Rw = &v case "w": req.W = &v case "dw": req.Dw = &v case "pw": req.Pw = &v } } } err, conn := obj.Bucket.client.request(req, rpbDelReq) if err != nil { return err } err = obj.Bucket.client.response(conn, req) if err != nil { return err } return nil } // Returns true if the object was fetched with multiple siblings (AllowMult=true on the bucket) func (obj *RObject) Conflict() bool { return obj.conflict } // Sets the values that returned from a pb.RpbGetResp in the RObject func (obj *RObject) setContent(resp *pb.RpbGetResp) { // Check if there are siblings if len(resp.Content) > 1 { // Mark as conflict, set fields obj.conflict = true obj.Siblings = make([]Sibling, len(resp.Content)) for i, content := range resp.Content { obj.Siblings[i].ContentType = string(content.ContentType) obj.Siblings[i].Data = content.Value obj.Siblings[i].Links = make([]Link, len(content.Links)) for j, link := range content.Links { obj.Siblings[i].Links[j] = Link{string(link.Bucket), string(link.Key), string(link.Tag)} } obj.Siblings[i].Meta = make(map[string]string) for _, meta := range content.Usermeta { obj.Siblings[i].Meta[string(meta.Key)] = string(meta.Value) } obj.Siblings[i].Indexes = make(map[string]string) for _, index := range content.Indexes { obj.Siblings[i].Indexes[string(index.Key)] = string(index.Value) } } } else if len(resp.Content) == 1 { // No conflict, set the fields in object directly obj.conflict = false obj.ContentType = string(resp.Content[0].ContentType) obj.Data = resp.Content[0].Value obj.Links = make([]Link, len(resp.Content[0].Links)) for j, link := range resp.Content[0].Links { obj.Links[j] = Link{string(link.Bucket), string(link.Key), string(link.Tag)} } obj.Meta = make(map[string]string) for _, meta := range resp.Content[0].Usermeta { obj.Meta[string(meta.Key)] = string(meta.Value) } obj.Indexes = make(map[string]string) for _, index := range resp.Content[0].Indexes { obj.Indexes[string(index.Key)] = string(index.Value) } } } // Add a link to another object (does not store the object, must explicitly call "Store()") func (obj *RObject) LinkTo(target *RObject, tag string) { if target.Bucket.name != "" && target.Key != "" { obj.Links = append(obj.Links, Link{target.Bucket.name, target.Key, tag}) } } // Add a link if it is not already in the Links slics, returns false if already present func (obj *RObject) AddLink(link Link) bool { for _, el := range obj.Links { if el.Bucket == link.Bucket && el.Key == link.Key && el.Tag == link.Tag { return false } } obj.Links = append(obj.Links, link) return true } // Get an object func (b *Bucket) Get(key string, options ...map[string]uint32) (obj *RObject, err error) { for i := 0; i < 3; i++ { req := &pb.RpbGetReq{ Bucket: []byte(b.name), Key: []byte(key), } for _, omap := range options { for k, v := range omap { switch k { case "r": req.R = &v case "pr": req.Pr = &v } } } err, conn := b.client.request(req, rpbGetReq) if err != nil { continue } resp := &pb.RpbGetResp{} err = b.client.response(conn, resp) if err != nil { continue } // If no Content is returned then the object was not found if len(resp.Content) == 0 { err = NotFound continue } // Create a new object and set the fields obj = &RObject{Key: key, Bucket: b, Vclock: resp.Vclock, Options: options} obj.setContent(resp) return obj, nil } return nil, err } // Reload an object if it has changed (new Vclock) func (obj *RObject) Reload() (err error) { req := &pb.RpbGetReq{ Bucket: []byte(obj.Bucket.name), Key: []byte(obj.Key), IfModified: obj.Vclock} for _, omap := range obj.Options { for k, v := range omap { switch k { case "r": req.R = &v case "pr": req.Pr = &v } } } err, conn := obj.Bucket.client.request(req, rpbGetReq) if err != nil { return err } resp := &pb.RpbGetResp{} err = obj.Bucket.client.response(conn, resp) if err != nil { return err } if resp.Unchanged != nil && *resp.Unchanged == true { return nil } // Object has new content, reload object obj.Vclock = resp.Vclock obj.setContent(resp) return nil }
package types import ( "math/big" sdk "github.com/irisnet/irishub/types" ) const RandPrec = 20 // the precision for generated random numbers // RNG is a random number generator type RNG interface { GetRand() sdk.Rat // interface which returns a random number between (0,1) } // PRNG represents a pseudo-random number implementation based on block for RNG type PRNG struct { BlockHash []byte // hash of some block BlockTimestamp int64 // timestamp of the next block TxInitiator sdk.AccAddress // address initiating the request tx } // MakePRNG constructs a PRNG func MakePRNG(blockHash []byte, blockTimestampt int64, txInitiator sdk.AccAddress) PRNG { return PRNG{ BlockHash: blockHash, BlockTimestamp: blockTimestampt, TxInitiator: txInitiator, } } // GetRand implements RNG func (p PRNG) GetRand() sdk.Rat { seedBT := big.NewInt(p.BlockTimestamp) seedBH := new(big.Int).Div(new(big.Int).SetBytes(sdk.SHA256(p.BlockHash)), seedBT) seedTI := new(big.Int).Div(new(big.Int).SetBytes(sdk.SHA256(p.TxInitiator)), seedBT) seedSum := new(big.Int).Add(seedBT, seedBH) seedSum = new(big.Int).Add(seedSum, seedTI) seed := new(big.Int).SetBytes(sdk.SHA256(seedSum.Bytes())) precision := new(big.Int).Exp(big.NewInt(10), big.NewInt(RandPrec), nil) // Generate a random number between [0,1) with `RandPrec` precision from seed rand := sdk.NewRatFromBigInt(new(big.Int).Mod(seed, precision), precision) return rand }
package main /** 面试题64. 求1+2+…+n 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 示例1: ``` 输入: n = 3 输出: 6 ``` 示例2: ``` 输入: n = 9 输出: 45 ``` 限制: - `1 <= n <= 10000` */ /** 一直想着递归时返回和,绕进去了没出来,其实还真是,在递归函数里面计算,在外部用个全局变量累加就可以了 */ func SumNums(n int) int { ans := 0 var sumR func(int) bool sumR = func(nu int) bool { ans += nu nu-- return nu > 0 && sumR(nu) } sumR(n) return ans }
package main import ( "bufio" "bytes" "log" "net/http" "os" "strconv" "strings" "time" "fmt" "flag" "errors" "github.com/BurntSushi/toml" "github.com/mattn/go-encoding" "golang.org/x/net/html" ) type Config struct { BaseUrl string FirstYear int SavePlace string } var ( sl = flag.Bool("sl", false, "save latest log") sa = flag.Bool("sa", false, "save all log") conf = setConfig() baseUrl = conf.BaseUrl firstYear = conf.FirstYear savePlace = conf.SavePlace ) var monthList = []string{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"} func walk(node *html.Node, buff *bytes.Buffer) { if node.Type == html.TextNode { data := strings.Trim(node.Data, "\r\n ") if data != "" { buff.WriteString("\n") buff.WriteString(data) } } for c := node.FirstChild; c != nil; c = c.NextSibling { switch strings.ToLower(node.Data) { case "script", "style", "title": continue } walk(c, buff) } } func getEUCJPText(url string) string { fmt.Println(url) res, err := http.Get(url) if err != nil { log.Fatal(err) } defer res.Body.Close() //200以外の場合は空文字列を返す if res.StatusCode != 200 { fmt.Printf("Statuscode:%v", res.StatusCode) return "" } else { br := bufio.NewReader(res.Body) r := encoding.GetEncoding("EUC-JP").NewDecoder().Reader(br) var buffer bytes.Buffer doc, err := html.Parse(r) if err != nil { log.Fatal(err) } walk(doc, &buffer) return buffer.String() } } func getUTF8Text(url string) string { fmt.Println(url) res, err := http.Get(url) if err != nil { log.Fatal(err) } defer res.Body.Close() //200以外の場合は空文字列を返す if res.StatusCode != 200 { fmt.Printf("Statuscode:%v", res.StatusCode) return "" } else { br := bufio.NewReader(res.Body) r := encoding.GetEncoding("UTF-8").NewDecoder().Reader(br) var buffer bytes.Buffer doc, err := html.Parse(r) if err != nil { log.Fatal(err) } walk(doc, &buffer) return buffer.String() } } func saveText(year string, month string, text string) { //年ごとのディレクトリの存在チェック。存在しなければディレクトリ作成。 _, err := os.Stat(savePlace + "/" + year) if err != nil && os.IsNotExist(err) { os.Mkdir(savePlace+"/"+year, 0755) fmt.Println("Create directory for " + year) } else if err != nil { log.Fatal(err) } else { fmt.Println("Directory for " + year + " already exists") } //月ごとのファイル作成 file, err := os.Create(savePlace + "/" + month + ".txt") if err != nil { log.Fatal(err) } file.Write([]byte(text)) file.Close() err = os.Rename(savePlace+"/"+month+".txt", savePlace+"/"+year+"/"+month+".txt") if err != nil { log.Fatal(err) } } func setConfig() Config { var conf Config _, err := toml.DecodeFile("config.toml", &conf) if err != nil { log.Fatal(err) } return conf } func createTxt(year int, month int) { yearAndMonth := strconv.Itoa(year) + monthList[month-1] url := baseUrl + `log/` + yearAndMonth + `.html` //2017年10月以降はutf-8。それより前はEUC-JP ym, err := strconv.Atoi(yearAndMonth) if err != nil { log.Fatal(err) } var text string if ym < 201710 { text = getEUCJPText(url) } else if ym >= 201710 { text = getUTF8Text(url) } // textが空ならページが存在しなかったということなので保存しない if text != "" { saveText(strconv.Itoa(year), monthList[month-1], text) } time.Sleep(time.Duration(1) * time.Second) } func saveAllLog(thisYear int) { for year := firstYear; year <= thisYear; year++ { for m := 1; m < 13; m++ { //2002年11月からスタート if year == 2002 && m != 12 { m = 11 } createTxt(year, m) } } } func saveLatest(thisYear int, thisMonth int) { url := baseUrl text := getUTF8Text(url) fmt.Println(text) lastYear, lastMonth := checkExistenceOfTxt(thisYear, thisMonth) //現在の年月と既存の最新データのものの差分を確認、現在までに新たに更新がなかったかチェック。 m := thisMonth y := thisYear for i := 1; ; i++ { m = m - 1 if y == lastYear && m == lastMonth { break } if m == 0 { m = 12 y = thisYear - i } createTxt(y, m) } //最新を保存 file, err := os.Create(savePlace + "/" + "latest" + ".txt") if err != nil { log.Fatal(err) } file.Write([]byte(text)) file.Close() } func checkExistenceOfTxt(year int, month int) (int, int) { //現在の月から1月まで順にファイルの存在チェック var m int var y int for i := 0; ; { m = month - i y = year //1月までチェックしたら前年の12月をチェック if m == 0 { y = year - 1 m = 12 } //.txtのファイル名は01のフォーマットのため配列から該当する値を設定 txtName := monthList[m-1] + ".txt" _, err := os.Stat(savePlace + "/" + strconv.Itoa(y) + "/" + txtName) if err != nil { i++ } else { break } } return y, m } func main() { flag.Parse() if *sa && *sl { log.Fatal(errors.New("too many flag")) } //保存先のフォルダが存在しなければ作成 _, err := os.Stat(savePlace) if err != nil { os.Mkdir(savePlace, 0777) } thisYear, err := strconv.Atoi(time.Now().Format("2006")) if err != nil { log.Fatal(err) } thisMonth, err := strconv.Atoi(time.Now().Format("01")) if err != nil { log.Fatal(err) } if *sa { saveAllLog(thisYear) } else if *sl { saveLatest(thisYear, thisMonth) } }
package protobuf //Status should be in all responses. type Status struct { Error error }
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func GetCategoryById(categoryId int64) (*model.Category, error) { category, err := factories.FindCategoryById(categoryId) if err != nil { return nil, err } if category == nil { return nil, errors.New("category does not exists") } return category, nil }
// Copyright (c) 2012 The Gocov Authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package main import ( "encoding/json" "errors" "flag" "fmt" "github.com/SunRunAway/gocov" "github.com/SunRunAway/gocov/gocovutil" "github.com/SunRunAway/gocov/parser" "go/ast" "go/build" goparser "go/parser" "go/printer" "go/token" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "sort" "strings" ) const gocovPackagePath = "github.com/SunRunAway/gocov" const instrumentedGocovPackagePath = "github.com/SunRunAway/gocov/instrumented" const unmanagedPackagePathRoot = "github.com/SunRunAway/gocov/unmanaged" func usage() { fmt.Fprintf(os.Stderr, "Usage:\n\n\tgocov command [arguments]\n\n") fmt.Fprintf(os.Stderr, "The commands are:\n\n") fmt.Fprintf(os.Stderr, "\tannotate\n") fmt.Fprintf(os.Stderr, "\ttest\n") fmt.Fprintf(os.Stderr, "\treport\n") fmt.Fprintf(os.Stderr, "\n") flag.PrintDefaults() os.Exit(2) } var ( testFlags = flag.NewFlagSet("test", flag.ExitOnError) testDepsFlag = testFlags.Bool( "deps", false, "instrument all package dependencies, including transitive") testExcludeFlag = testFlags.String( "exclude", "", "packages to exclude, separated by comma") testExcludeGorootFlag = testFlags.Bool( "exclude-goroot", false, "exclude packages in GOROOT from instrumentation") testWorkFlag = testFlags.Bool( "work", false, "print the name of the temporary work directory "+ "and do not delete it when exiting") testTagsFlag = testFlags.String( "tags", "", "a list of build tags to consider satisfied during the build") testRunFlag = testFlags.String( "run", "", "run only those tests and examples matching the regular "+ "expression.") testTimeoutFlag = testFlags.String( "timeout", "", "if a test runs longer than t, panic.") testParallelFlag = testFlags.Int( "parallel", runtime.GOMAXPROCS(-1), "run tests in parallel (see: go help testflag)") testPackageParallelFlag = testFlags.Int( "p", runtime.NumCPU(), "build and test up to N packages in parallel") verbose bool verboseX bool ) func init() { testFlags.BoolVar(&verbose, "v", false, "be verbose") testFlags.BoolVar(&verboseX, "x", false, "be verbose and print the commands") } func errorf(f string, args ...interface{}) { fmt.Fprintf(os.Stderr, f, args...) } func verbosef(f string, args ...interface{}) { if verbose { fmt.Fprintf(os.Stderr, f, args...) } } type instrumenter struct { goroot string // temporary GOROOT context build.Context excluded []string instrumented map[string]*gocov.Package processed map[string]bool workingdir string // path of package currently being processed } func putenv(env []string, key, value string) []string { for i, s := range env { if strings.HasPrefix(s, key+"=") { env[i] = key + "=" + value return env } } return append(env, key+"="+value) } func (in *instrumenter) parsePackage(path string, fset *token.FileSet) (*build.Package, *ast.Package, error) { p, err := in.context.Import(path, in.workingdir, 0) if err != nil { return nil, nil, err } goFiles := append(p.GoFiles[:], p.CgoFiles...) sort.Strings(goFiles) filter := func(f os.FileInfo) bool { name := f.Name() i := sort.SearchStrings(goFiles, name) return i < len(goFiles) && goFiles[i] == name } mode := goparser.DeclarationErrors | goparser.ParseComments pkgs, err := goparser.ParseDir(fset, p.Dir, filter, mode) if err != nil { return nil, nil, err } return p, pkgs[p.Name], err } func symlinkHierarchy(src, dst string) error { // First check if the destination exists; if so, bail out // before doing a potentially expensive walk. if _, err := os.Stat(dst); err == nil { return nil } fn := func(path string, info os.FileInfo, err error) error { if err != nil { return err } rel, err := filepath.Rel(src, path) if err != nil { return err } target := filepath.Join(dst, rel) if _, err = os.Stat(target); err == nil { return nil } // Walk directory symlinks. Check for target // existence above and os.MkdirAll below guards // against infinite recursion. mode := info.Mode() if mode&os.ModeSymlink == os.ModeSymlink { realpath, err := os.Readlink(path) if err != nil { return err } if !filepath.IsAbs(realpath) { dir := filepath.Dir(path) realpath = filepath.Join(dir, realpath) } info, err := os.Stat(realpath) if err != nil { return err } if info.IsDir() { err = os.MkdirAll(target, 0700) if err != nil { return err } // Symlink contents, as the MkdirAll above // and the initial existence check will work // against each other. f, err := os.Open(realpath) if err != nil { return err } names, err := f.Readdirnames(-1) f.Close() if err != nil { return err } for _, name := range names { realpath := filepath.Join(realpath, name) target := filepath.Join(target, name) err = symlinkHierarchy(realpath, target) if err != nil { return err } } return nil } } if mode.IsDir() { return os.MkdirAll(target, 0700) } else { err = os.Symlink(path, target) if err != nil { srcfile, err := os.Open(path) if err != nil { return err } defer srcfile.Close() dstfile, err := os.OpenFile( target, os.O_RDWR|os.O_CREATE, 0600) if err != nil { return err } defer dstfile.Close() _, err = io.Copy(dstfile, srcfile) return err } } return nil } return filepath.Walk(src, fn) } // The only packages that can't be instrumented are those that the core gocov // package depends upon (and fake packages like C, unsafe). func instrumentable(path string) bool { switch path { case "C", "runtime", "sync", "sync/atomic", "syscall", "unsafe": // Can't instrument the packages that gocov depends on. return false } return true } // abspkgpath converts a possibly local import path to an absolute package path. func (in *instrumenter) abspkgpath(pkgpath string) (string, error) { if pkgpath == "C" || pkgpath == "unsafe" { return pkgpath, nil } p, err := in.context.Import(pkgpath, in.workingdir, build.FindOnly) if err != nil { return "", err } if build.IsLocalImport(p.ImportPath) { // If a local import was provided to go/build, but // it exists inside a GOPATH, go/build will fill in // the GOPATH import path. Otherwise it will remain // a local import path. err = errors.New(` Coverage testing of packages outside of GOPATH is not currently supported. See: https://github.com/SunRunAway/gocov/issues/30 `) return "", err } return p.ImportPath, nil } func instrumentedPackagePath(pkgpath string) string { // All instrumented packages import gocov. If we want to // instrumented gocov itself, we must change its name so // it can import (the uninstrumented version of) itself. if pkgpath == gocovPackagePath { return instrumentedGocovPackagePath } return pkgpath } func (in *instrumenter) instrumentPackage(pkgpath string, testPackage bool) error { if already := in.processed[pkgpath]; already { return nil } defer func() { if _, instrumented := in.instrumented[pkgpath]; !instrumented { in.processed[pkgpath] = true } }() // Certain packages should always be skipped. if !instrumentable(pkgpath) { verbosef("skipping uninstrumentable package %q\n", pkgpath) return nil } // Ignore explicitly excluded packages. if i := sort.SearchStrings(in.excluded, pkgpath); i < len(in.excluded) { if in.excluded[i] == pkgpath { verbosef("skipping excluded package %q\n", pkgpath) return nil } } fset := token.NewFileSet() buildpkg, pkg, err := in.parsePackage(pkgpath, fset) if err != nil { return err } if !testPackage && (buildpkg.Goroot && *testExcludeGorootFlag) { verbosef("skipping GOROOT package %q\n", pkgpath) return nil } in.instrumented[pkgpath] = nil // created in first instrumented file verbosef("instrumenting package %q\n", pkgpath) if testPackage && len(buildpkg.TestGoFiles)+len(buildpkg.XTestGoFiles) == 0 { verbosef("skipping %q because no test files\n", buildpkg.Name) return nil } // Set a "working directory", for resolving relative imports. defer func(oldworkingdir string) { in.workingdir = oldworkingdir }(in.workingdir) in.workingdir = buildpkg.Dir if *testDepsFlag { imports := buildpkg.Imports[:] if testPackage { imports = append(imports, buildpkg.TestImports...) imports = append(imports, buildpkg.XTestImports...) } for _, subpkgpath := range imports { subpkgpath, err = in.abspkgpath(subpkgpath) if err != nil { return err } if _, done := in.instrumented[subpkgpath]; !done { err = in.instrumentPackage(subpkgpath, false) if err != nil { return err } } } } // Fix imports in test files, but don't instrument them. rewriteFiles := make(map[string]*ast.File) if testPackage { testGoFiles := buildpkg.TestGoFiles[:] testGoFiles = append(testGoFiles, buildpkg.XTestGoFiles...) for _, filename := range testGoFiles { path := filepath.Join(buildpkg.Dir, filename) mode := goparser.DeclarationErrors | goparser.ParseComments file, err := goparser.ParseFile(fset, path, nil, mode) if err != nil { return err } in.redirectImports(file) rewriteFiles[filename] = file } } // Clone the directory structure, symlinking files (if possible), // otherwise copying the files. Instrumented files will replace // the symlinks with new files. // // If we instrument package x/y, and x/y uses package x, then // we must be sure to also symlink the files in package x, // as it'll be picked up in the instrumented GOROOT. parts := strings.Split(pkgpath, "/") var partpath string for i, part := range parts { if i == 0 { partpath = part } else { partpath += "/" + part } p, err := in.context.Import(partpath, in.workingdir, 0) if err != nil && i+1 == len(parts) { return err } if err == nil && p.SrcRoot == buildpkg.SrcRoot { ipkgpath := instrumentedPackagePath(partpath) clonedir := filepath.Join(in.goroot, "src", "pkg", ipkgpath) err = symlinkHierarchy(p.Dir, clonedir) if err != nil { return err } // You might think we can break here, but we can't; // since "instrumentedPackagePath" may change the // package path between source and destination, we // must check each level in the hierarchy individually. } } // pkg == nil if there are only test files. ipkgpath := instrumentedPackagePath(pkgpath) clonedir := filepath.Join(in.goroot, "src", "pkg", ipkgpath) if pkg != nil { for filename, f := range pkg.Files { err := in.instrumentFile(f, fset, pkgpath) if err != nil { return err } rewriteFiles[filename] = f } } for filename, f := range rewriteFiles { filepath := filepath.Join(clonedir, filepath.Base(filename)) err = os.Remove(filepath) if err != nil { return err } file, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE, 0600) if err != nil { return err } printer.Fprint(file, fset, f) // TODO check err? err = file.Close() if err != nil { return err } } return nil } func marshalJson(packages []*gocov.Package) ([]byte, error) { return json.Marshal(struct{ Packages []*gocov.Package }{packages}) } func unmarshalJson(data []byte) (packages []*gocov.Package, err error) { result := &struct{ Packages []*gocov.Package }{} err = json.Unmarshal(data, result) if err == nil { packages = result.Packages } return } // packagesAndTestargs returns a list of package paths // and a list of arguments to pass on to "go test". func packagesAndTestargs() ([]string, []string, error) { // Everything before the first arg starting with "-" // is considered a package, and everything after/including // is an argument to pass on to "go test". var packagepaths, gotestargs []string if testFlags.NArg() > 0 { split := -1 args := testFlags.Args() for i, arg := range args { if strings.HasPrefix(arg, "-") { split = i break } } if split >= 0 { packagepaths = args[:split] gotestargs = args[split:] } else { packagepaths = args } } if len(packagepaths) == 0 { packagepaths = []string{"."} } // Run "go list <packagepaths>" to expand "...", evaluate // "std", "all", etc. Also, "go list" collapses duplicates. args := []string{"list"} if *testTagsFlag != "" { tags := strings.Fields(*testTagsFlag) args = append(args, "-tags") args = append(args, tags...) } args = append(args, packagepaths...) output, err := exec.Command("go", args...).CombinedOutput() if err != nil { fmt.Fprintln(os.Stderr, string(output)) return nil, nil, err } else { packagepaths = strings.Fields(string(output)) } // FIXME we don't currently handle testing cmd/*, as they // are not regular packages. This means "gocov test std" // can't work unless we ignore cmd/* or until we implement // support. var prunedpaths []string for _, p := range packagepaths { if !strings.HasPrefix(p, "cmd/") { prunedpaths = append(prunedpaths, p) } else { fmt.Fprintf(os.Stderr, "warning: support for cmd/* not supported, ignoring %s\n", p) } } packagepaths = prunedpaths return packagepaths, gotestargs, nil } func instrumentAndTest() (rc int) { testFlags.Parse(os.Args[2:]) packagePaths, gotestArgs, err := packagesAndTestargs() if err != nil { errorf("failed to process package list: %s\n", err) return 1 } tempDir, err := ioutil.TempDir("", "gocov") if err != nil { errorf("failed to create temporary GOROOT: %s\n", err) return 1 } if *testWorkFlag { fmt.Fprintf(os.Stderr, "WORK=%s\n", tempDir) } else { defer func() { err := os.RemoveAll(tempDir) if err != nil { fmt.Fprintf(os.Stderr, "warning: failed to delete temporary GOROOT (%s)\n", tempDir) } }() } goroot := runtime.GOROOT() for _, name := range [...]string{"src", "pkg"} { dir := filepath.Join(goroot, name) err = symlinkHierarchy(dir, filepath.Join(tempDir, name)) if err != nil { errorf("failed to create $GOROOT/%s: %s\n", name, err) return 1 } } // Copy gocov into the temporary GOROOT, since otherwise it'll // be eclipsed by the instrumented packages root. Use the default // build context here since gocov doesn't use custom build tags. if p, err := build.Import(gocovPackagePath, "", build.FindOnly); err == nil { err = symlinkHierarchy(p.Dir, filepath.Join(tempDir, "src", "pkg", gocovPackagePath)) if err != nil { errorf("failed to symlink gocov: %s\n", err) return 1 } } else { errorf("failed to locate gocov: %s\n", err) return 1 } var excluded []string if len(*testExcludeFlag) > 0 { excluded = strings.Split(*testExcludeFlag, ",") sort.Strings(excluded) } cwd, err := os.Getwd() if err != nil { errorf("failed to determine current working directory: %s\n", err) } context := build.Default if *testTagsFlag != "" { context.BuildTags = strings.Fields(*testTagsFlag) } in := &instrumenter{ goroot: tempDir, context: context, instrumented: make(map[string]*gocov.Package), excluded: excluded, processed: make(map[string]bool), workingdir: cwd, } instrumentedPackagePaths := make([]string, len(packagePaths)) for i, packagePath := range packagePaths { var absPackagePath string absPackagePath, err = in.abspkgpath(packagePath) if err != nil { errorf("failed to resolve package path(%s): %s\n", packagePath, err) return 1 } packagePath = absPackagePath err = in.instrumentPackage(packagePath, true) if err != nil { errorf("failed to instrument package(%s): %s\n", packagePath, err) return 1 } instrumentedPackagePaths[i] = instrumentedPackagePath(packagePath) } ninstrumented := 0 for _, pkg := range in.instrumented { if pkg != nil { ninstrumented++ } } if ninstrumented == 0 { errorf("error: no packages were instrumented\n") return 1 } // Temporarily rename package archives in // $GOPATH, for instrumented packages. for _, packagePath := range packagePaths { p, err := in.context.Import(packagePath, in.workingdir, build.FindOnly) if err == nil && !p.Goroot && p.PkgObj != "" { verbosef("temporarily renaming package object %s\n", p.PkgObj) err = os.Rename(p.PkgObj, p.PkgObj+".gocov") if err != nil { verbosef(" - failed to rename: %v\n", err) } else { defer func(pkgobj string) { verbosef("restoring package object %s\n", pkgobj) err = os.Rename(pkgobj+".gocov", pkgobj) if err != nil { verbosef(" - failed to restore package object: %v\n", err) } }(p.PkgObj) } } } // Run "go test". const gocovOutPrefix = "gocov.out" env := os.Environ() env = putenv(env, "GOCOVOUT", filepath.Join(tempDir, gocovOutPrefix)) env = putenv(env, "GOROOT", tempDir) args := []string{"test"} if verbose { args = append(args, "-v") } if verboseX { args = append(args, "-x") } if *testTagsFlag != "" { args = append(args, "-tags", *testTagsFlag) } if *testRunFlag != "" { args = append(args, "-run", *testRunFlag) } if *testTimeoutFlag != "" { args = append(args, "-timeout", *testTimeoutFlag) } args = append(args, "-parallel", fmt.Sprint(*testParallelFlag)) args = append(args, "-p", fmt.Sprint(*testPackageParallelFlag)) args = append(args, instrumentedPackagePaths...) args = append(args, gotestArgs...) // First run with "-i" to avoid the warning // about out-of-date packages. testiargs := append([]string{args[0], "-i"}, args[1:]...) cmd := exec.Command("go", testiargs...) cmd.Env = env cmd.Stdout = os.Stderr cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { errorf("go test -i failed: %s\n", err) return 1 } else { // Now run "go test" normally. cmd = exec.Command("go", args...) cmd.Env = env cmd.Stdout = os.Stderr cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { errorf("go test failed: %s\n", err) return 1 } } tempDirFile, err := os.Open(tempDir) if err != nil { errorf("failed to open output directory: %s\n", err) return 1 } defer tempDirFile.Close() names, err := tempDirFile.Readdirnames(-1) if err != nil { errorf("failed to list output directory: %s\n", err) return 1 } var allpackages gocovutil.Packages for _, name := range names { if !strings.HasPrefix(name, gocovOutPrefix) { continue } outfilePath := filepath.Join(tempDir, name) packages, err := parser.ParseTrace(outfilePath) if err != nil { errorf("failed to parse gocov output: %s\n", err) return 1 } for _, p := range packages { allpackages.AddPackage(p) } } data, err := marshalJson(allpackages) if err != nil { errorf("failed to format as JSON: %s\n", err) return 1 } else { fmt.Println(string(data)) } return } func main() { flag.Usage = usage flag.Parse() if verboseX { verbose = true } command := "" if flag.NArg() > 0 { command = flag.Arg(0) switch command { case "annotate": os.Exit(annotateSource()) case "report": os.Exit(reportCoverage()) case "test": os.Exit(instrumentAndTest()) //case "run" default: fmt.Fprintf(os.Stderr, "Unknown command: %#q\n\n", command) usage() } } else { usage() } }
package main var dx []int var dy []int // DFS时判断访问坐标是否合法 func judge(A [][]int, x, y int) bool { if len(A) == 0 { return false } m, n := len(A), len(A[0]) if x < 0 || y < 0 || x >= m || y >= n { return false } if A[x][y] == 0 || A[x][y] == 2 { return false } return true } // 把第一个岛屿赋值为2 func DFS(A [][]int, x, y int) { if !judge(A, x, y) { return } A[x][y] = 2 for i := 0; i < len(dx); i++ { DFS(A, x+dx[i], y+dy[i]) } } type Node struct { x, y int } func shortestBridge(A [][]int) int { dx = []int{1, -1, 0, 0} dy = []int{0, 0, -1, 1} if len(A) == 0 { return 0 } m, n := len(A), len(A[0]) findFirstIsland: for i := 0; i < m; i++ { for t := 0; t < n; t++ { // 找到属于第一个岛屿的一格,将第一个岛屿全标记2 if A[i][t] == 1 { DFS(A, i, t) break findFirstIsland } } } // 将第二个岛屿的所有点入队并标记 hasBeenInQueue := make(map[int]bool) queue := make([]Node, 0) for i := 0; i < m; i++ { for t := 0; t < n; t++ { if A[i][t] == 1 { queue = append(queue, Node{i, t}) hasBeenInQueue[hash(i, t)] = true } } } level := 0 for len(queue) != 0 { size := len(queue) for size != 0 { size-- top := queue[0] queue = queue[1:] // 表示已经连接到第一个岛屿了 if A[top.x][top.y] == 2 { return level - 1 } for i := 0; i < len(dx); i++ { nx, ny := top.x+dx[i], top.y+dy[i] hashNumber := hash(nx, ny) if nx < 0 || ny < 0 || nx >= m || ny >= n || hasBeenInQueue[hashNumber] { continue } queue = append(queue, Node{nx, ny}) hasBeenInQueue[hashNumber] = true } } level++ } return 0 } func hash(x, y int) int { return (x << 20) | y } /* 题目链接: https://leetcode-cn.com/problems/shortest-bridge/submissions/ 最短的桥 */ /* 总结: 1. 这题的思路如下: (1) 先找到其中一个岛屿的一块,之后通过这一块,使用DFS向外拓展,将该岛屿的每一块都标记为2。 (2) 将另外一个岛屿的所有坐标入队,进行BFS,直到遇到第一个岛屿的部分(此时这部分的标识是2了) (3) BFS层数-1就是桥的长度了。 2. 这题写得真长... */
package main import "fmt" type Person struct { int string height float32 } func main() { p := Person{23, "Evan", 1.75} fmt.Println(p.int, p.string, p.height) fmt.Println(p) }
package models import ( "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func init() { beego.SetLogger("console", "") beego.SetLogFuncCall(true) beego.BeeLogger.SetLogFuncCallDepth(4) beego.Trace("init()") orm.Debug = true orm.RegisterDriver("mysql", orm.DR_MySQL) // register model orm.RegisterModel(new(Artist)) orm.RegisterModel(new(Album)) orm.RegisterModel(new(Record)) orm.RegisterModel(new(Track)) // set default database maxIdle := 30 maxConn := 30 orm.RegisterDataBase("default", "mysql", "root:123456@/golden_times?charset=utf8", maxIdle, maxConn) //orm.RegisterDataBase("default", "mysql", "root:123456@tcp(10.180.120.63:3306)/golden_times?charset=utf8", maxIdle, maxConn) orm.RunCommand() RunSyncdb() } func RunSyncdb() { // 数据库删名 name := "default" // drop table 后再建表 force := true // 打印执行过程 verbose := true // 遇刡错诨立即迒回 err := orm.RunSyncdb(name, force, verbose) if err != nil { fmt.Println(err) } }
package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/c-bata/go-prompt" "github.com/doctori/music-migrator/deezer" ) var s Spotify var d deezer.Deezer func mainCompleter(d prompt.Document) []prompt.Suggest { s := []prompt.Suggest{ {Text: "spotify", Description: "spotify related stuff"}, {Text: "deezer", Description: "deezer related stuff"}, {Text: "quit", Description: "leave me alone !"}, } operands := strings.Split(d.TextBeforeCursor(), " ") if len(operands) > 1 { switch operands[0] { case "spotify": s = []prompt.Suggest{ {Text: "login", Description: "login to spotify"}, {Text: "playlist", Description: "list playlists"}, {Text: "loved-tracks", Description: "list all the loved tracks"}, } case "deezer": s = []prompt.Suggest{ {Text: "login", Description: "login do deezer"}, {Text: "playlist", Description: "list playlists"}, {Text: "loved-tracks", Description: "List all the loved tracks"}, } } } return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true) } func mainSwitcher(input string) { switch strings.Trim(input, " ") { case "quit": fmt.Println("bye bye ") os.Exit(0) case "spotify": fmt.Println("Spotify mode") case "spotify login": s.Connect() case "spotify playlist": if !s.Connected { s.Connect() } s.ListPlaylists() case "spotify loved-tracks": if !s.Connected { s.Connect() } s.PrintSpotifyLovedTracks() case "deezer login": d.Connect() case "deezer playlist": if !d.Connected { d.Connect() } printDeezerPlaylists() case "deezer loved-tracks": if !d.Connected { d.Connect() } printDeezerLovedTracks() default: fmt.Printf("What do you want me to do with %s\n", input) } } func main() { fmt.Println("Hello world") p := prompt.New( mainSwitcher, mainCompleter, ) p.Run() os.Exit(0) } func init() { d.Init() s.Init() // first start an HTTP server http.HandleFunc("/spotify-callback", s.completeAuth) http.HandleFunc("/deezer-callback", d.CompleteAuth) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Println("Got request for:", r.URL.String()) }) go http.ListenAndServe("127.0.0.1:8080", nil) }
package haproxyctl import ( "fmt" "reflect" "strconv" "strings" ) var ( truth_list = []string{"true", "1", "yes", "y", "on"} false_list = []string{"false", "0", "no", "n", "off"} bool_map map[string]bool ) func init() { bool_map = make(map[string]bool, 0) for _, k := range truth_list { bool_map[k] = true } for _, k := range false_list { bool_map[k] = false } } func BoolVal(s string) (bool, error) { k := strings.ToLower(s) v, found := bool_map[k] if found { return v, nil } return v, fmt.Errorf("invalid value %s", s) } func ScanMap(m map[string]string, dest interface{}) error { v := reflect.ValueOf(dest) base := reflect.Indirect(v) for i := 0; i < base.NumField(); i++ { df := base.Field(i) dt := df.Type() var field_name string tag := base.Type().Field(i).Tag.Get("scan") if tag == "" { // field_name = strings.ToLower(base.Type().Field(i).Name) field_name = base.Type().Field(i).Name } else { field_name = tag } v, ok := m[field_name] if ok == false { continue } if v == "" { continue } switch dt.Kind() { case reflect.Int: nv, err := strconv.ParseInt(v, 10, 64) if err != nil { return fmt.Errorf("%s parameter: parse error", field_name) } df.SetInt(nv) case reflect.Bool: b, err := BoolVal(v) if err != nil { return fmt.Errorf("%s parameter: parse bool error", field_name) } df.SetBool(b) case reflect.String: df.SetString(v) } } return nil }
package handlers import ( "log" "net/http" "github.com/rest_service_task/impl/errors" "github.com/rest_service_task/impl/structs" ) //swagger:parameters CreateUser type CreateUserParams struct { // Required: true // in: body Body structs.User } // swagger:route POST /create user CreateUser // Method for creation new user // Responses: // default: errorResponse // 200: func (hs *Handlers) Create(w http.ResponseWriter, r *http.Request) { var user structs.User err := ReadBody(r, &user) if err != nil { hs.logger.Println(err.Error()) e := errors.NewError(errors.BAD_REQUEST_ERROR) if fatal := errors.WriteHttpErrorMessage(w, http.StatusBadRequest, e); fatal != nil { log.Fatal(fatal.Error()) } return } if user.PassInfo == nil { e := errors.NewError(errors.BAD_REQUEST_ERROR) if fatal := errors.WriteHttpErrorMessage(w, http.StatusBadRequest, e); fatal != nil { log.Fatal(fatal.Error()) } return } passHash := HashPassword(*user.PassInfo) user.PassInfo = &passHash err = hs.database.CreateUser(user.FirstName, user.LastName, user.Login, *user.PassInfo, user.Age, user.Phone) if err != nil { hs.logger.Println(err.Error()) e := &errors.ErrorResponse{ Code: errors.INTERNAL_ERROR, Message: err.Error(), } if fatal := errors.WriteHttpErrorMessage(w, http.StatusInternalServerError, e); fatal != nil { log.Fatal(fatal.Error()) } return } w.WriteHeader(http.StatusOK) return }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package bf import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestBitField(t *testing.T) { Convey("BitField", t, func() { bf := Make(2000) Convey("Should be sized right", func() { So(bf.Size(), ShouldEqual, 2000) So(len(bf.Data), ShouldEqual, 32) }) Convey("Should be empty", func() { So(bf.All(false), ShouldBeTrue) So(bf.Data[0], ShouldEqual, 0) So(bf.CountSet(), ShouldEqual, 0) So(bf.IsSet(20), ShouldBeFalse) So(bf.IsSet(200001), ShouldBeFalse) Convey("and be unset", func() { for i := uint64(0); i < 20; i++ { So(bf.IsSet(i), ShouldBeFalse) } }) }) Convey("Boundary conditions are caught", func() { So(bf.Set(2000), ShouldNotBeNil) So(bf.Clear(2000), ShouldNotBeNil) }) Convey("and setting [0, 1, 19, 197, 4]", func() { So(bf.Set(0), ShouldBeNil) So(bf.Set(1), ShouldBeNil) So(bf.Set(19), ShouldBeNil) So(bf.Set(197), ShouldBeNil) So(bf.Set(1999), ShouldBeNil) So(bf.Set(4), ShouldBeNil) Convey("should count correctly", func() { So(bf.CountSet(), ShouldEqual, 6) }) Convey("should retrieve correctly", func() { So(bf.IsSet(2), ShouldBeFalse) So(bf.IsSet(18), ShouldBeFalse) So(bf.IsSet(0), ShouldBeTrue) So(bf.IsSet(1), ShouldBeTrue) So(bf.IsSet(4), ShouldBeTrue) So(bf.IsSet(19), ShouldBeTrue) So(bf.IsSet(197), ShouldBeTrue) So(bf.IsSet(1999), ShouldBeTrue) }) Convey("should clear correctly", func() { So(bf.Clear(3), ShouldBeNil) So(bf.Clear(4), ShouldBeNil) So(bf.Clear(197), ShouldBeNil) So(bf.IsSet(2), ShouldBeFalse) So(bf.IsSet(3), ShouldBeFalse) So(bf.IsSet(18), ShouldBeFalse) So(bf.IsSet(4), ShouldBeFalse) So(bf.IsSet(197), ShouldBeFalse) So(bf.IsSet(0), ShouldBeTrue) So(bf.IsSet(1), ShouldBeTrue) So(bf.IsSet(19), ShouldBeTrue) So(bf.CountSet(), ShouldEqual, 4) }) }) }) }
package cmd import ( "errors" "fmt" zabbix "github.com/canghai908/zabbix-go" _ "github.com/go-sql-driver/mysql" "github.com/google/uuid" _ "github.com/lib/pq" "github.com/manifoldco/promptui" "github.com/urfave/cli/v2" "gopkg.in/ini.v1" "os" "strconv" "strings" ) const qrencode = `###################################################################### ###################################################################### ###################################################################### ###### ###### ###### ## ## ###### ###### ########## #### ######## ## #### ########## ###### ###### ## ## ## #### #### #### ## ## ## ###### ###### ## ## #### #### ## ######## ## ## ## ###### ###### ## ## #### #### ###### ## #### ## ## ###### ###### ########## ###### ## ## ## ########## ###### ###### ## ## ## ## ## ## ## ## ###### ###################### #### ## ## ## ## ###################### ###### ## ###### #### ###### ########## ###### ######## #### ## ## #### #### #### ###### ########## ## #### #### ## #### ## ## ###### ######## ###### ###### ## ###### ## ## ######## ########## ## ## ## ## #### #### ## #### ## ###### ###### ###### #### #### ## ## ## #### ## ###### ########## #### #### ## ######## #### #### ###### ########## ## #### ## ## ## ## ## ## ######## ########## #### ## ## ## ## ###### ###### ########## #### ## ## #### ## ###### ## ###### ###### ## ## ## ## ########## ## ###### ######## ## ## ###### ## ########## ## ######## ###### ######## ## #### ###### ###### ############## ###################### ## ## ## ## ###### ## ###### ###### ## ######## #### ## ## ## ## ###### ###### ########## ## ## ## ## ## ###### ###### ###### ###### ## ## ## ## #### #### ############ ###### ## ## #### ## ## #### #### ###### ###### ## ## ## ## ## ## ## #### ###### ###### ########## ## #### ###### ## ########## ######## ###### ## ## ## #### #### ###### ###################################################################### ###################################################################### ######################################################################` var ( // Init cli Init = &cli.Command{ Name: "init", Usage: "Init config file", Action: AppInit, } API = &zabbix.API{} Cfg = &ini.File{} ) //AppInit func AppInit(*cli.Context) error { DB: validate := func(input string) error { _, err := strconv.ParseFloat(input, 64) if err != nil { return errors.New("Invalid number") } return nil } //db type ProDbtype := promptui.Select{ Label: "Select ZbxTable DB Type", Items: []string{"mysql", "postgresql"}, HideHelp: true, } _, dbtype, err := ProDbtype.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //db host ProDbhost := promptui.Prompt{ Label: "DBHost", Default: "localhost", AllowEdit: true, } dbhost, err := ProDbhost.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //db name ProDBname := promptui.Prompt{ Label: "DBName", Default: "zbxtable", AllowEdit: true, } dbname, err := ProDBname.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //db user ProDBuser := promptui.Prompt{ Label: "DBUser", Default: "zbxtable", AllowEdit: true, } dbuser, err := ProDBuser.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //db pass ProDBpass := promptui.Prompt{ Label: "DBPass", Default: "zbxtablepwd123", AllowEdit: true, } dbpass, err := ProDBpass.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //switch DefaultPort var DefaultPort string switch dbtype { case "mysql": DefaultPort = "3306" case "postgresql": DefaultPort = "5432" } //db port ProDBport := promptui.Prompt{ Label: "DBPort", Default: DefaultPort, AllowEdit: true, Validate: validate, } dbport, err := ProDBport.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //db check err = CheckDb(dbtype, dbhost, dbuser, dbpass, dbname, dbport) if err != nil { fmt.Println(err) fmt.Println("Connection to database " + dbname + " failed,please reconfigure the database connection information.") goto DB } fmt.Println("Connected to database " + dbname + " successfully!") WEB: //zabbix web url ProZbxWeb := promptui.Prompt{ Label: "Zabbix Web URL", Default: "http://", AllowEdit: true, } zabbix_web, err := ProZbxWeb.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //zabbix username ProZbxUser := promptui.Prompt{ Label: "Zabbix Username", Default: "Admin", AllowEdit: true, } zabbix_user, err := ProZbxUser.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //zabbix Password ProZbxPass := promptui.Prompt{ Label: "Zabbix Password", Default: "zabbix", AllowEdit: true, } zabbix_pass, err := ProZbxPass.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } //check zabbix connection version, err := CheckZabbixAPI(zabbix_web, zabbix_user, zabbix_pass) if err != nil { fmt.Println(err) fmt.Println("Connection to Zabbix API " + zabbix_web + " /api_jsonrpc.php failed,please reconfigure the zabbix web connection information.") goto WEB } fmt.Println("Connected to Zabbix API successfully!Zabbix version is ", version) fmt.Println("The configuration information is as follows:") fmt.Println("ZbxTable dbtype:", dbtype) fmt.Println("ZbxTable dbhost:", dbhost) fmt.Println("ZbxTable dbname:", dbname) fmt.Println("ZbxTable dbuser:", dbuser) fmt.Println("ZbxTable dbpass:", dbpass) fmt.Println("ZbxTable dbport:", dbport) fmt.Println("Zabbix Web URL:", zabbix_web) fmt.Println("Zabbix Username:", zabbix_user) fmt.Println("Zabbix Password:", zabbix_pass) prompt := promptui.Select{ Label: "Is the configuration information correct[Yes/No]?", Items: []string{"Yes", "No"}, HideHelp: true, } _, result, err := prompt.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return err } switch result { case "Yes": token := strings.ReplaceAll(uuid.New().String(), "-", "") err = WriteConf(zabbix_web, zabbix_user, zabbix_pass, dbtype, dbhost, dbuser, dbpass, dbname, dbport, "", "", "", token) if err != nil { fmt.Printf("write config file failed %v\n", err) return err } fmt.Println("The configuration file ./conf/app.conf is generated successfully!") fmt.Println("Follow WeChat public account to get the latest news!") fmt.Println(qrencode) case "No": goto DB } return nil } //Write config files func WriteConf(zabbix_web, zabbix_user, zabbix_pass, dbtype, dbhost, dbuser, dbpass, dbname, dbport, httpport, runmode, timeout, token string) error { cfg := ini.Empty() //zbxtable info cfg.Section("").Key("appname").Comment = "zbxtable" //migrate httpport if httpport == "" { cfg.Section("").NewKey("httpport", "8084") } else { cfg.Section("").NewKey("httpport", httpport) } //migrate runmode if runmode == "" { cfg.Section("").NewKey("runmode", "prod") } else { cfg.Section("").NewKey("runmode", runmode) } //migrate timeout if timeout == "" { cfg.Section("").NewKey("timeout", "12") } else { cfg.Section("").NewKey("timeout", timeout) } cfg.Section("").NewKey("appname", "zbxtable") cfg.Section("").NewKey("token", token) cfg.Section("").NewKey("copyrequestbody", "true") //database info cfg.Section("").Key("dbtype").Comment = "database" cfg.Section("").NewKey("dbtype", dbtype) cfg.Section("").NewKey("dbhost", dbhost) cfg.Section("").NewKey("dbuser", dbuser) cfg.Section("").NewKey("dbpass", dbpass) cfg.Section("").NewKey("dbname", dbname) cfg.Section("").NewKey("dbport", dbport) //zabbix info cfg.Section("").Key("zabbix_web").Comment = "zabbix" cfg.Section("").NewKey("zabbix_web", zabbix_web) cfg.Section("").NewKey("zabbix_user", zabbix_user) cfg.Section("").NewKey("zabbix_pass", zabbix_pass) // check confpath := "./conf" _, err := os.Stat(confpath) if err != nil { err := os.MkdirAll(confpath, 0755) if err != nil { return err } } err = cfg.SaveTo("./conf/app.conf") if err != nil { return err } return nil }
package db_test import ( "testing" "bitbucket.org/matchmove/go-database" _ "github.com/erikstmartin/go-testdb" "github.com/jmoiron/sqlx" "github.com/stretchr/testify/assert" ) func TestNewDB(t *testing.T) { d, err := db.New("testdb", "") assert.Nil(t, err) assert.Equal(t, d.Driver, "testdb") assert.Equal(t, d.Open, "") assert.IsType(t, &sqlx.DB{}, d.Connection) // errors _, err = db.New("mysql", "u:p(tcp)") assert.Error(t, err) } func TestDB_Connect(t *testing.T) { db := &db.DB{ Driver: "testdb", Open: "", } c, err := db.Connect() assert.IsType(t, &sqlx.DB{}, c, "") assert.Nil(t, err, "") }
package main import ( "fmt" "sort" "strconv" "strings" "github.com/bwmarrin/discordgo" ) // process commands that can only be run in dms func dmCommand(s *discordgo.Session, m *discordgo.MessageCreate, command string) { switch command { case "help": dmHelpCommand(s, m) case "ping": pingCommand(s, m) case "register": registerUserCommand(s, m) case "lastplayed": lastPlayingCommand(s, m) case "lastloved": lastLovedCommand(s, m) case "lastregister": registerUserLastFMCommand(s, m) case "bigletters": makeBigLettersCommand(s, m) default: defaultHelpCommand(s, m) } } // process commands as normal user func userCommand(s *discordgo.Session, m *discordgo.MessageCreate, command string) { switch command { case "help": serverHelpCommand(s, m) case "user": userInfoCommand(s, m) case "server": serverInfoCommand(s, m) case "addrole": addRoleCommand(s, m) case "delrole": delRoleCommand(s, m) case "roles": listAvailableRolesCommand(s, m) case "myroles": listMyRolesCommand(s, m) default: dmCommand(s, m, command) } } // process commands as admin func adminCommand(s *discordgo.Session, m *discordgo.MessageCreate, command string) { switch command { case "purge": purgeCommand(s, m) logCommand(s, m) case "addlog": addLoggingChannelCommand(s, m) logCommand(s, m) case "removelog": removeLoggingChannelCommand(s, m) logCommand(s, m) case "kick": kickUserCommand(s, m) logCommand(s, m) case "ban": banUserCommand(s, m) logCommand(s, m) case "help": adminHelpCommand(s, m) case "deregister": deregisterUserCommand(s, m) logCommand(s, m) case "mute": muteCommand(s, m) logCommand(s, m) case "unmute": unmuteCommand(s, m) logCommand(s, m) default: userCommand(s, m, command) } } // process commands for ops func opsCommand(s *discordgo.Session, m *discordgo.MessageCreate, command string) { switch command { case "massregister": tempMassRegisterCommand(s, m) logCommand(s, m) case "repush-names": pushNamesCommand(s, m) logCommand(s, m) case "push-user": pushUserCommand(s, m) logCommand(s, m) case "reload-bot": reloadBotCommand(s, m) logCommand(s, m) case "help": opsHelpCommand(s, m) default: adminCommand(s, m, command) } } func dmHelpCommand(s *discordgo.Session, m *discordgo.MessageCreate) { s.ChannelMessageSendEmbed(m.ChannelID, getDMHelpEmbed()) } func serverHelpCommand(s *discordgo.Session, m *discordgo.MessageCreate) { s.ChannelMessageSendEmbed(m.ChannelID, getServerHelpEmbed()) } func adminHelpCommand(s *discordgo.Session, m *discordgo.MessageCreate) { s.ChannelMessageSendEmbed(m.ChannelID, getAdminHelpEmbed()) } func opsHelpCommand(s *discordgo.Session, m *discordgo.MessageCreate) { s.ChannelMessageSendEmbed(m.ChannelID, getOpsHelpEmbed()) } func defaultHelpCommand(s *discordgo.Session, m *discordgo.MessageCreate) { // this is evaluation to check and see if it contains a number at the start // if it does then it's probably someone typing something like $20 command := strings.TrimPrefix(m.Content, loadedConfigData.Prefix) firstChar := string([]rune(command)[0]) if !strings.ContainsAny(firstChar, "0123456789 ") { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("%s isn't a valid command. Use %shelp to learn more", strings.TrimPrefix(m.Content, loadedConfigData.Prefix), loadedConfigData.Prefix)) } } func pingCommand(s *discordgo.Session, m *discordgo.MessageCreate) { s.ChannelMessageSend(m.ChannelID, "Pong!") } func avatarCommand(s *discordgo.Session, m *discordgo.MessageCreate) { if len(m.Mentions) > 0 { if len(m.Mentions) > 4 { s.ChannelMessageSend(m.ChannelID, "Make sure to mention less than 5 users") return } for _, u := range m.Mentions { s.ChannelMessageSendEmbed(m.ChannelID, getAvatarEmbed(u)) } return } s.ChannelMessageSendEmbed(m.ChannelID, getAvatarEmbed(m.Author)) } func purgeCommand(s *discordgo.Session, m *discordgo.MessageCreate) { fields := strings.Fields(m.Content) n, err := strconv.Atoi(fields[len(fields)-1]) if err != nil { s.ChannelMessageSend(m.ChannelID, "Make sure a number of messages to delete is specified at the end of the command") return } if n > 99 || n < 1 { s.ChannelMessageSend(m.ChannelID, "Please enter a number between 1 and 99 (inclusive)") return } var messageIDs []string messages, err := s.ChannelMessages(m.ChannelID, n+1, "", "", "") if err != nil { fmt.Printf("Error getting messages: %s", err) return } for _, element := range messages { messageIDs = append(messageIDs, element.ID) } err = s.ChannelMessagesBulkDelete(m.ChannelID, messageIDs) if err != nil { fmt.Printf("Error deleting messages in channel %s: %s", m.ChannelID, err) s.ChannelMessageSend(m.ChannelID, "Unable to delete messages. Please check permissions and try again") return } } func userInfoCommand(s *discordgo.Session, m *discordgo.MessageCreate) { g, err := s.Guild(m.GuildID) if err != nil { fmt.Printf("Error getting guild: %s", err) return } if len(m.Mentions) > 0 { if len(m.Mentions) > 4 { s.ChannelMessageSend(m.ChannelID, "Make sure to mention less than 5 users") return } for _, u := range m.Mentions { s.ChannelMessageSendEmbed(m.ChannelID, getUserEmbed(u, s, g)) } return } s.ChannelMessageSendEmbed(m.ChannelID, getUserEmbed(m.Author, s, g)) } func removeUserCommand(s *discordgo.Session, m *discordgo.MessageCreate, ban bool) { method := "kick" if ban { method = "ban" } fields := strings.SplitN(strings.TrimPrefix(m.Content, loadedConfigData.Prefix), " ", 3) if len(fields) < 3 { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Please make sure to specify a user and reason when giving the %s", method)) return } reason := fields[2] if len(m.Mentions) < 1 { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Make sure to specify a user to %s", method)) return } user := m.Mentions[0] dmUser(s, *user, fmt.Sprintf("You have been given the %s because %s", method, reason)) if ban { dmUser(s, *user, "next time, follow the goddamn rules :)\nhttps://www.youtube.com/watch?v=FXPKJUE86d0") } else { dmUser(s, *user, "get dabbed on\nhttps://cdn.discordapp.com/attachments/593650772227653672/631587659604688897/dabremy.png") } var err error if ban { err = s.GuildBanCreateWithReason(m.GuildID, user.ID, reason, 1) } else { err = s.GuildMemberDeleteWithReason(m.GuildID, user.ID, reason) } if err != nil { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Unable to %s %s for reason %s", method, user.Mention(), reason)) fmt.Printf("Error when giving user %s the %s , %s", user.Mention(), method, err) return } prevMessage, err := s.ChannelMessages(m.ChannelID, 1, "", "", "") if err != nil || len(prevMessage) < 1 { fmt.Printf("Error retrieving previous message: %s", err) } err = s.ChannelMessageDelete(m.ChannelID, prevMessage[0].ID) if err != nil { fmt.Printf("Error deleting previous message: %s", err) } s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("%s was given the %s because of reason: %s", user.Mention(), method, reason)) } func kickUserCommand(s *discordgo.Session, m *discordgo.MessageCreate) { removeUserCommand(s, m, false) } func banUserCommand(s *discordgo.Session, m *discordgo.MessageCreate) { removeUserCommand(s, m, true) } func serverInfoCommand(s *discordgo.Session, m *discordgo.MessageCreate) { g, err := s.Guild(m.GuildID) if err != nil { fmt.Printf("Error getting guild: %s", err) return } guildOwner, err := s.User(g.OwnerID) if err != nil { fmt.Printf("Error getting guild owner: %s", err) return } s.ChannelMessageSendEmbed(m.ChannelID, getServerEmbed(s, g, guildOwner)) } func addLoggingChannelCommand(s *discordgo.Session, m *discordgo.MessageCreate) { err := addLoggingChannel(m.ChannelID) if err == nil { s.ChannelMessageSend(m.ChannelID, "This channel will now be used for logging") } else if err == errChannelRegistered { s.ChannelMessageSend(m.ChannelID, "This channel is already set up for logging") } else { s.ChannelMessageSend(m.ChannelID, "There was an error while setting up this channel for logging") fmt.Printf("Error while configuring %s for logging: %s", m.ChannelID, err) } } func removeLoggingChannelCommand(s *discordgo.Session, m *discordgo.MessageCreate) { err := removeLoggingChannel(m.ChannelID) if err == nil { s.ChannelMessageSend(m.ChannelID, "This channel will no longer be used for logging") } else if err == errChannelNotRegistered { s.ChannelMessageSend(m.ChannelID, "This channel has not yet been configured for logging") } else { s.ChannelMessageSend(m.ChannelID, "There was an error while removing this channel's logging status") fmt.Printf("Error while removing %s from logging: %s", m.ChannelID, err) } } func tempMassRegisterCommand(s *discordgo.Session, m *discordgo.MessageCreate) { guild, err := s.State.Guild(m.GuildID) if err != nil { fmt.Printf("Error getting guild: %s", err) return } for _, mem := range guild.Members { if !mem.User.Bot { c, err := s.UserChannelCreate(mem.User.ID) if err != nil { fmt.Printf("Error creating channel: %s", err) } else if _, ok := loadedUserData.Users[mem.User.ID]; !ok { _, err := s.ChannelMessageSend(c.ID, fmt.Sprintf("Please send me `%sregister {your first and last name} {grade as a number}` (e.g. `%sregister Jono Jenkens 12`)", loadedConfigData.Prefix, loadedConfigData.Prefix)) if err != nil { fmt.Printf("Error sending message to user: %s", err) } } } } } func listAvailableRolesCommand(s *discordgo.Session, m *discordgo.MessageCreate) { roles, err := getAvailableRoles(s, m, m.Author) if err != nil { s.ChannelMessageSend(m.ChannelID, "Unable to query roles.") fmt.Printf("Unable to query roles: %s", err) return } s.ChannelMessageSendEmbed(m.ChannelID, getRolesEmbed(roles, "Available Roles")) } func listMyRolesCommand(s *discordgo.Session, m *discordgo.MessageCreate) { mem, err := s.GuildMember(m.GuildID, m.Author.ID) if err != nil { fmt.Printf("Error getting member: %s", err) return } roles := mem.Roles sortedroles := make([]*discordgo.Role, len(roles)) for i, role := range roles { r, err := s.State.Role(m.GuildID, role) if err != nil { fmt.Printf("Error finding role: %s", err) return } sortedroles[i] = r } sort.SliceStable(sortedroles, func(i, j int) bool { return sortedroles[i].Position > sortedroles[j].Position }) s.ChannelMessageSendEmbed(m.ChannelID, getRolesEmbed(sortedroles, "Your Roles")) } func addRoleCommand(s *discordgo.Session, m *discordgo.MessageCreate) { parseUpdateRole(s, m, false) } func delRoleCommand(s *discordgo.Session, m *discordgo.MessageCreate) { parseUpdateRole(s, m, true) } func pushNamesCommand(s *discordgo.Session, m *discordgo.MessageCreate) { // iterate through all stored users and push the user joined string to the names channel for _, userID := range loadedUserData.Users { discordUser, err := s.User(userID.DiscordID) if err != nil { // press f in chat fmt.Printf("Unable to make user object for %v: %s", userID, err) } else { pushNewUser(discordUser, s) } } } func muteCommand(s *discordgo.Session, m *discordgo.MessageCreate) { // automatically add a configured muted role to a user if len(m.Mentions) <= 0 { s.ChannelMessageSend(m.ChannelID, "Make sure to mention a user to mute") return } err := setMuted(s, m, m.Mentions[0], true) if err != nil { s.ChannelMessageSend(m.ChannelID, "Unable to mute user") return } s.ChannelMessageSend(m.ChannelID, "User muted.") } func unmuteCommand(s *discordgo.Session, m *discordgo.MessageCreate) { // automatically remove a muted role from a user if len(m.Mentions) <= 0 { s.ChannelMessageSend(m.ChannelID, "Make sure to mention a user to unmute") return } err := setMuted(s, m, m.Mentions[0], false) if err != nil { s.ChannelMessageSend(m.ChannelID, "Unable to unmute user") return } s.ChannelMessageSend(m.ChannelID, "User unmuted.") } func lastPlayingCommand(s *discordgo.Session, m *discordgo.MessageCreate) { userStruct, err := getUserStruct(m.Author) if err != nil { s.ChannelMessageSend(m.ChannelID, "Unable to query user. Are you registered?") return } lastListened, err := getUserLastListened(userStruct) if err != nil { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Unable to get last.fm data for user `%s`. Please make sure you've linked accounts.", userStruct.LastFmAccount)) return } lastPlayingEmbed := getLastFMTrackEmbed(lastListened) s.ChannelMessageSend(m.ChannelID, "Most recently scrobbled song:") s.ChannelMessageSendEmbed(m.ChannelID, lastPlayingEmbed) } func lastLovedCommand(s *discordgo.Session, m *discordgo.MessageCreate) { userStruct, err := getUserStruct(m.Author) if err != nil { s.ChannelMessageSend(m.ChannelID, "Unable to query user. Are you registered?") return } lastListened, err := getUserLastLoved(userStruct) if err != nil { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Unable to get last.fm data for user `%s`. Please make sure you've linked accounts.", userStruct.LastFmAccount)) return } lastLovedEmbed := getLastFMTrackEmbed(lastListened) s.ChannelMessageSend(m.ChannelID, "Most recently loved song:") s.ChannelMessageSendEmbed(m.ChannelID, lastLovedEmbed) } func registerUserLastFMCommand(s *discordgo.Session, m *discordgo.MessageCreate) { fields := strings.SplitN(strings.TrimPrefix(m.Content, loadedConfigData.Prefix), " ", 2) if len(fields) < 2 { s.ChannelMessageSend(m.ChannelID, "Ensure that your username is included") return } user := m.Author lastFMUserName := fields[1] err := registerUserLastFM(user, lastFMUserName) if err != nil { s.ChannelMessageSend(m.ChannelID, "Unable to link accounts.") return } s.ChannelMessageSend(m.ChannelID, "Linked accounts successfully!") } func makeBigLettersCommand(s *discordgo.Session, m *discordgo.MessageCreate) { fields := strings.SplitN(strings.ToLower(strings.TrimPrefix(m.Content, loadedConfigData.Prefix)), " ", 2) if len(fields) < 2 { s.ChannelMessageSend(m.ChannelID, "Please make sure you enter text to be transformed") return } initial := fields[1] message := "" for _, char := range initial { if char != ' ' { if char == 'b' { message += ":b:" } else if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') { message += fmt.Sprintf(":regional_indicator_%c:", char) continue } else { message += fmt.Sprintf("%c", char) } } message += " " } s.ChannelMessageSend(m.ChannelID, message) } func pushUserCommand(s *discordgo.Session, m *discordgo.MessageCreate) { if len(m.Mentions) <= 0 { s.ChannelMessageSend(m.ChannelID, "Make sure to mention a user to push the name for") return } pushNewUser(m.Mentions[0], s) s.ChannelMessageSend(m.ChannelID, "User pushed") } func reloadBotCommand(s *discordgo.Session, m *discordgo.MessageCreate) { // reload bot resources in place if err := loadUsers(); err != nil { s.ChannelMessageSend(m.ChannelID, "error loading user file") } if err := loadConfig(); err != nil { s.ChannelMessageSend(m.ChannelID, "error loading config file") } else { startBotConfig(s) } }
package cmd import ( "log" "net/http" ) func NewServer() *Server { return &Server{ mux: http.NewServeMux(), server: &http.Server{ Addr: ":8000", }, } } type Server struct { server *http.Server mux *http.ServeMux } func (s *Server) ListenAndServe() { s.routes() s.server.Handler = s.mux log.Fatal(s.server.ListenAndServeTLS("cert/server.crt", "cert/server.key")) } func (s *Server) routes() { s.mux.HandleFunc("/hello", s.handleHello()) s.mux.HandleFunc("/timeline", s.handleTimeline()) } func (s *Server) handleHello() http.HandlerFunc { // you can prepare something. log.Printf("hello handler is registered.") return func(w http.ResponseWriter, r *http.Request) { log.Printf("Got connection: %s", r.Proto) w.Write([]byte("Hello")) } } func (s *Server) handleTimeline() http.HandlerFunc { // you can prepare something. log.Printf("timeline handler is registered.") return func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: w.Write([]byte("timeline get")) case http.MethodPost: w.Write([]byte("timeline post")) case http.MethodPut: w.Write([]byte("timeline put")) case http.MethodDelete: w.Write([]byte("timeline delete")) default: w.Write([]byte("timeline error")) } } }
package main import ( "net" "fmt" // "path/filepath" ) func echoServer(c net.Conn) { for { // buf := make([]byte, 512) // nr, err := c.Read(buf) // if err != nil { // return // } // addr := filepath.Base(c.LocalAddr().String()) // extension := filepath.Ext(addr) // proc := addr[0 : len(addr)-len(extension)] // fmt.Printf("%s %s %s", addr, extension, proc) // data := buf[0:nr] // fmt.Printf("Received: %v", string(data)) _, err := c.Write([]byte("shicong")) if err != nil { panic("Write: " + err.Error()) } buf := make([]byte, 512) nr, err := c.Read(buf) if err != nil { return } data := buf[0:nr] fmt.Printf("Received: %v", string(data)) } } func main() { l, err := net.Listen("unix", "/Volumes/HardWare/GOLearning/DistrubuteAgent/src/SimpleSocket/ipc/echo.sock") if err != nil { println("listen error", err) return } for { fd, err := l.Accept() if err != nil { println("accept error", err) return } go echoServer(fd) } }
package config import ( "html/template" "io" "net/http" "time" "github.com/gorilla/securecookie" "github.com/labstack/echo" "golang.org/x/crypto/bcrypt" ) type M map[string]interface{} type Renderer struct { template *template.Template debug bool location string } //secureCookie var sc = securecookie.New([]byte("very-secret"), []byte("a-lot-secret-yay")) //---------------------------------render html---------------------------------// func NewRenderer(location string, debug bool) *Renderer { tpl := new(Renderer) tpl.location = location tpl.debug = debug tpl.ReloadTemplates() return tpl } func (t *Renderer) ReloadTemplates() { t.template = template.Must(template.ParseGlob(t.location)) } func (t *Renderer) Render( w io.Writer, name string, data interface{}, c echo.Context, ) error { if t.debug { t.ReloadTemplates() } return t.template.ExecuteTemplate(w, name, data) } //---------------------------------render html---------------------------------// //---------------------------------password bcrypt---------------------------------// func HashPassword(password string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) return string(bytes), err } func CheckPasswordHash(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil } //---------------------------------password bcrypt---------------------------------// //secureCookie func SetCookie(c echo.Context, name string, data M) error { encoded, err := sc.Encode(name, data) if err != nil { return err } cookie := &http.Cookie{ Name: name, Value: encoded, Path: "/", Secure: false, HttpOnly: true, Expires: time.Now().Add(1 * time.Hour), } http.SetCookie(c.Response(), cookie) return nil } func GetCookie(c echo.Context, name string) (M, error) { cookie, err := c.Request().Cookie(name) if err == nil { data := M{} if err = sc.Decode(name, cookie.Value, &data); err == nil { return data, nil } } return nil, err }
/* Copyright 2019 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kogito import ( "context" kogitoclient "knative.dev/eventing-kogito/pkg/kogito/injection/client" reconcilersource "knative.dev/eventing/pkg/reconciler/source" "knative.dev/eventing-kogito/pkg/apis/kogito/v1alpha1" "github.com/kelseyhightower/envconfig" "k8s.io/client-go/tools/cache" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" "knative.dev/pkg/logging" "knative.dev/pkg/resolver" "knative.dev/eventing-kogito/pkg/reconciler" kogitosourceinformer "knative.dev/eventing-kogito/pkg/client/injection/informers/kogito/v1alpha1/kogitosource" "knative.dev/eventing-kogito/pkg/client/injection/reconciler/kogito/v1alpha1/kogitosource" kogitoruntimeinformer "knative.dev/eventing-kogito/pkg/kogito/injection/informers/app/v1beta1/kogitoruntime" kubeclient "knative.dev/pkg/client/injection/kube/client" ) // NewController initializes the controller and is called by the generated code // Registers event handlers to enqueue events func NewController( ctx context.Context, cmw configmap.Watcher, ) *controller.Impl { kogitoSourceInformer := kogitosourceinformer.Get(ctx) kogitoRuntimeInformer := kogitoruntimeinformer.Get(ctx) r := &Reconciler{ krr: &reconciler.KogitoRuntimeReconciler{KubeClientSet: kubeclient.Get(ctx), KogitoClientSet: kogitoclient.Get(ctx)}, // Config accessor takes care of tracing/config/logging config propagation to the receive adapter configAccessor: reconcilersource.WatchConfigurations(ctx, "kogito-source", cmw), } if err := envconfig.Process("", r); err != nil { logging.FromContext(ctx).Panicf("required environment variable is not defined: %v", err) } impl := kogitosource.NewImpl(ctx, r) r.sinkResolver = resolver.NewURIResolverFromTracker(ctx, impl.Tracker) logging.FromContext(ctx).Info("Setting up event handlers") kogitoSourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) kogitoRuntimeInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ FilterFunc: controller.FilterControllerGK(v1alpha1.Kind("KogitoSource")), Handler: controller.HandleAll(impl.EnqueueControllerOf), }) return impl }
/* package server когда нажали ентер клиент посылает сигнал серверу о том, что один игрок подключился. Тем временем на клиенте создаётся поле, но змеек ещё нет. Ждём ответ от сервера. Сервер принимает подключение, добавляет его в свой пул подключений и начинает ждать 30сек что бы подключился хотя бы ещё один чел. Тем временем сервер считает координаты размещения первого игрока и посылает их, так же посылает число обратного отсчёта. После того как подключились два чела и прошло 30 сек сервер рассылает координаты всех объектов каждому клиенту. Каждый тик мы отправляем направление змейки на сервер, он их отрабатывает. Каждый тик мы принимаем координаты от сервера и отрисовываем их. */ package main import ( "net/http" "github.com/AlexanderKorovaev/snake/server/core" "github.com/AlexanderKorovaev/snake/server/handlers" ) // подумать // жлбавить конфиг файлы func main() { // сохраним необходимые настройки из конфига core.InitializationGlobals("config.ini") // запустим обратный отсчёт // в целом тут просто надо, что бы посчитался отсчёт и // сообщил клиенту, что больше подключаться нельзя. // т.е. при следующих подключениях к /initiate он будет сообщать, что время вышло. // таким образом сервер будет предохраняться от новых подключений во время игры go core.Countdown() http.HandleFunc("/initiate", handlers.InitiateGame) http.HandleFunc("/playersTurn", handlers.PlayersTurn) http.ListenAndServe(":2000", nil) }
package cart type PromotionDiscount func(Cart) float64 func PriceWithPromotions(cart Cart, promotions []func(Cart) float64) float64 { total := PriceWithoutPromotions(cart) discount := 0.0 for _, f := range promotions { discount += f(cart) } return total - discount } func BeltAre15PercentOffIf2OrMoreTrousers(cart Cart) float64 { discount := 0.0 quantity, some := cart.quantity["belts"] if some != true { return discount } beltPrice, _ := cart.GetPrice("belts") discount = beltPrice * float64(quantity) * 0.15 return discount } func ShirtsAre45DollarsIf2OrMoreShirts(cart Cart) float64 { discount := 0.0 quantity, some := cart.quantity["shirts"] if some != true { return discount } shirtPrice, _ := cart.GetPrice("shirts") shirtDiscount := shirtPrice - 45.0 discount = float64(quantity-2) * shirtDiscount return discount } func PriceWithoutPromotions(cart Cart) float64 { total := 0.0 for name, quantity := range cart.quantity { price, _ := cart.GetPrice(name) total = total + price*float64(quantity) } return total }
/* Copyright 2015 Google Inc. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd */ package main import ( "flag" "fmt" "os" "os/signal" "syscall" "time" "github.com/google/cups-connector/cups" "github.com/google/cups-connector/gcp" "github.com/google/cups-connector/lib" "github.com/google/cups-connector/manager" "github.com/google/cups-connector/monitor" "github.com/google/cups-connector/snmp" "github.com/google/cups-connector/xmpp" "github.com/golang/glog" ) func main() { flag.Parse() defer glog.Flush() glog.Error(lib.FullName) fmt.Println(lib.FullName) config, err := lib.ConfigFromFile() if err != nil { glog.Fatal(err) } if _, err := os.Stat(config.MonitorSocketFilename); !os.IsNotExist(err) { if err != nil { glog.Fatal(err) } glog.Fatalf( "A connector is already running, or the monitoring socket %s wasn't cleaned up properly", config.MonitorSocketFilename) } cupsConnectTimeout, err := time.ParseDuration(config.CUPSConnectTimeout) if err != nil { glog.Fatalf("Failed to parse cups connect timeout: %s", err) } gcpXMPPPingTimeout, err := time.ParseDuration(config.XMPPPingTimeout) if err != nil { glog.Fatalf("Failed to parse xmpp ping timeout: %s", err) } gcpXMPPPingIntervalDefault, err := time.ParseDuration(config.XMPPPingIntervalDefault) if err != nil { glog.Fatalf("Failed to parse xmpp ping interval default: %s", err) } gcp, err := gcp.NewGoogleCloudPrint(config.GCPBaseURL, config.RobotRefreshToken, config.UserRefreshToken, config.ProxyName, config.GCPOAuthClientID, config.GCPOAuthClientSecret, config.GCPOAuthAuthURL, config.GCPOAuthTokenURL, gcpXMPPPingIntervalDefault) if err != nil { glog.Fatal(err) } xmpp, err := xmpp.NewXMPP(config.XMPPJID, config.ProxyName, config.XMPPServer, config.XMPPPort, gcpXMPPPingTimeout, gcpXMPPPingIntervalDefault, gcp.GetRobotAccessToken) if err != nil { glog.Fatal(err) } defer xmpp.Quit() cups, err := cups.NewCUPS(config.CopyPrinterInfoToDisplayName, config.CUPSPrinterAttributes, config.CUPSMaxConnections, cupsConnectTimeout, gcp.Translate) if err != nil { glog.Fatal(err) } defer cups.Quit() var snmpManager *snmp.SNMPManager if config.SNMPEnable { glog.Info("SNMP enabled") snmpManager, err = snmp.NewSNMPManager(config.SNMPCommunity, config.SNMPMaxConnections) if err != nil { glog.Fatal(err) } defer snmpManager.Quit() } pm, err := manager.NewPrinterManager(cups, gcp, xmpp, snmpManager, config.CUPSPrinterPollInterval, config.GCPMaxConcurrentDownloads, config.CUPSJobQueueSize, config.CUPSJobFullUsername, config.CUPSIgnoreRawPrinters, config.ShareScope) if err != nil { glog.Fatal(err) } defer pm.Quit() m, err := monitor.NewMonitor(cups, gcp, pm, config.MonitorSocketFilename) if err != nil { glog.Fatal(err) } defer m.Quit() glog.Errorf("Ready to rock as proxy '%s'\n", config.ProxyName) fmt.Printf("Ready to rock as proxy '%s'\n", config.ProxyName) waitIndefinitely() glog.Error("Shutting down") fmt.Println("") fmt.Println("Shutting down") } // Blocks until Ctrl-C or SIGTERM. func waitIndefinitely() { ch := make(chan os.Signal) signal.Notify(ch, os.Interrupt, syscall.SIGTERM) <-ch go func() { // In case the process doesn't die very quickly, wait for a second termination request. <-ch fmt.Println("Second termination request received") os.Exit(1) }() }
package main func convert(s string, numRows int) string { str := []byte(s) res := "" if numRows == 1 { return s } cycle := 2*numRows - 2 for i := 0; i < numRows; i++ { for j := 0; j+i < len(str); j += cycle { res += string(str[j+i]) if i != 0 && i != numRows-1 && j+cycle-i < len(str) { res += string(str[j+cycle-i]) } } } return res }
/* Copyright 2020 The SuperEdge Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package server import ( "github.com/munnerz/goautoneg" "k8s.io/apimachinery/pkg/runtime" ) func (s *interceptorServer) parseAccept(header string, accepted []runtime.SerializerInfo) (runtime.SerializerInfo, bool) { if len(header) == 0 && len(accepted) > 0 { return accepted[0], true } clauses := goautoneg.ParseAccept(header) for i := range clauses { clause := &clauses[i] for i := range accepted { accepts := &accepted[i] switch { case clause.Type == accepts.MediaTypeType && clause.SubType == accepts.MediaTypeSubType, clause.Type == accepts.MediaTypeType && clause.SubType == "*", clause.Type == "*" && clause.SubType == "*": return *accepts, true } } } return runtime.SerializerInfo{}, false }
/* package core модуль globals хранит объекты для общего доступа */ package game import ( "github.com/JoelOtter/termloop" ) // GameScreen глобальная переменная которая хранит основные объекты уровня // в начале игры мы передаём эту переменную в termloop и меняя сзначеия этой // переменной мы можем менять происходящее на уровне var gameScreen *game // termloopGame переменная игры нам нужна для динамической смены левелов var termloopGame *termloop.Game // width ширина поля, по факту граница рисуется на 34 пикселе, и змейке достаётся 33 в ширину var width int // high высота поля, по факту граница рисуется на 14 пикселе, и змейке достаётся 13 в ширину var high int // константа для хранения имени клиента var clientID string = getOutboundIP()
package payment import ( "github.com/gucastiliao/special-case-pattern/pkg/charge" "github.com/gucastiliao/special-case-pattern/pkg/model" ) type PaymentReceiver struct{} func (p PaymentReceiver) Charge(subscription model.Subscription) error { charge := charge.NewChargeFactory(subscription) return charge.Execute() }
package fuzzbuzz import ( "io/ioutil" "testing" ) func BenchmarkFirst(b *testing.B) { for i := 0; i < b.N; i++ { firstSolution(ioutil.Discard) } } func BenchmarkSecond(b *testing.B) { for i := 0; i < b.N; i++ { secondSolution(ioutil.Discard) } } func BenchmarkThird(b *testing.B) { for i := 0; i < b.N; i++ { thirdSolution(ioutil.Discard) } }
package ac // https://leetcode-cn.com/problems/stream-of-characters/ type StreamChecker struct { root *Node current *Node } func Constructor(words []string) StreamChecker { root := Compile(words) return StreamChecker{root, root} } func (this *StreamChecker) Query(letter byte) bool { node := this.current for node.children[letter] == nil && node != this.root { node = node.fail } node = node.children[letter] if node == nil { this.current = this.root return false } this.current = node if node.match { return true } for suffix := node.matchSuffix; suffix != nil; suffix = suffix.matchSuffix { return true } return false }
package models //1. やると決めたことを最後までやりきる //2. 無責任な人を見るとイライラする //3. 「〇〇すべき」という言葉をよく使っている //4. 厳しいしつけを受けてきた //5. わたしはホメ上手だと思う //6. 聞き役になることが多い //7. 困っている人をみるとなんとかしてあげたくなる //8. ボランティア活動などに参加するのが好き //9. 結果を予測して準備する //10.他の人はどうするだろう?と客観視する //11.物事を分析して、事実に基づいて考える //12.上手くいかない時でもあまりイライラしない //13.欲しいものは手に入れないと気が済まない //14.人のことを見ただけで、なんとなくこの人はこんな人かなと感じる //15.将来のイメージを妄想することが好き //16.みんなでワイワイ集まるのが好き //17.嫌なことを嫌と言えないことが多い //18.リーダー的な人の意見に従う方が楽 //19.人からの視線や評価がいつも気になる //20.何か頼まれると先延ばしにしがち //はい ->2 //どちらでもない->1 //いいえ    ->0 type Personality struct { One string Two string Three string Four string Five string Six string Seven string Eight string Nine string Ten string Eleven string Twelve string Thirteen string Fourteen string Fifteen string Sixteen string Seventeen string Eighteen string Nineteen string Twenty string RigorRate int AcceptabilityRate int LogicalityRate int FreedomRate int CoordinationRate int }
package main import ( "bufio" "github.com/codegangsta/cli" "io/ioutil" "log" "os" "path" "strings" "text/template" ) type EnumCase struct { Name string RawValue string } type EnumType struct { Name string Values []EnumCase Nested []EnumType } func parseFolder(filepath string) (EnumType, error) { files, err := ioutil.ReadDir(filepath) if err != nil { return EnumType{}, err } enumCases := []EnumCase{} enumTypes := []EnumType{} for _, f := range files { if strings.HasSuffix(f.Name(), "imageset") { rawValue := strings.Split(f.Name(), ".")[0] name := strings.Title(rawValue) name = strings.Replace(name, "_", "__", -1) name = strings.Replace(name, "-", "_", -1) enum := EnumCase{name, rawValue} enumCases = append(enumCases, enum) } else if !strings.Contains(f.Name(), ".") { folderName := path.Join(filepath, f.Name()) enumType, err := parseFolder(folderName) if err != nil { return EnumType{}, err } enumTypes = append(enumTypes, enumType) } } _, file := path.Split(filepath) name := strings.Title(file) return EnumType{name, enumCases, enumTypes}, nil } func main() { app := cli.NewApp() l := log.New(os.Stderr, "", 0) app.Name = "resourceful" app.Usage = "Add strong typing to imageNamed: in Swift apps" app.Flags = []cli.Flag{ cli.StringFlag{ Name: "input, i", Value: "Images.xcassets", Usage: "The xcassets directory that contains your app's images", EnvVar: "SCRIPT_INPUT_FILE_0", }, cli.StringFlag{ Name: "output, o", Value: "Resourceful.swift", Usage: "The destination file for generated Swift code", EnvVar: "SCRIPT_OUTPUT_FILE_0", }, } app.Commands = []cli.Command{ { Name: "warn", Usage: "Generate xcode warnings for usage of imageNamed", Flags: []cli.Flag{ cli.StringFlag{ Name: "warndirectory, w", Usage: "The directory to search for legacy usage of imageNamed", EnvVar: "SRCROOT", }, }, Action: func(c *cli.Context) { err := warn(c.String("warndirectory")) if err != nil { l.Println("Error detecting warnings.") os.Exit(1) } }, }, } app.Action = func(c *cli.Context) { enumType, err := parseFolder(c.String("input")) if err != nil { l.Println("Error parsing input file.") os.Exit(1) } enumType.Name = "Image" f, err := os.Create(c.String("output")) if err != nil { l.Println("Error writing output file") os.Exit(1) } defer f.Close() writer := bufio.NewWriter(f) templ := template.Must(template.New("swiftTemplate").Parse(swiftTemplate)) err = templ.Execute(writer, enumType) if err != nil { panic(err) } writer.Flush() } app.Run(os.Args) }
package config //软件状态机 var ( s_0_Init = StateAndInfo{ 0, "软件初始化状态", } s_1_Creating = StateAndInfo{ 1, "软件安装中", } s_2_Created = StateAndInfo{ 2, "软件已经安装", } s_3_Starting = StateAndInfo{ 3, "软件正在启动", } s_4_Started = StateAndInfo{ 4, "软件已经启动", } s_5_Offing = StateAndInfo{ 5, "软件正在关闭", } s_6_Offed = StateAndInfo{ 6, "软件已经关闭", } s_7_Deteling = StateAndInfo{ 7, "软件删除中", } s_8_Deleted = StateAndInfo{ 8, "软件已经删除", } ) func C_S_0_Init() *StateAndInfo { return &s_0_Init } func C_S_1_Creating() *StateAndInfo { return &s_1_Creating } func C_S_2_Created() *StateAndInfo { return &s_2_Created } func C_S_3_Starting() *StateAndInfo { return &s_3_Starting } func C_S_4_Started() *StateAndInfo { return &s_4_Started } func C_S_5_Offing() *StateAndInfo { return &s_5_Offing } func C_S_6_Offed() *StateAndInfo { return &s_6_Offed } func C_S_7_Deteling() *StateAndInfo { return &s_7_Deteling } func C_S_8_Deleted() *StateAndInfo { return &s_8_Deleted } func C_Check_Software_State(state int32) bool { for _, node := range []int32{s_0_Init.State, s_1_Creating.State, s_2_Created.State, s_3_Starting.State, s_4_Started.State, s_5_Offing.State, s_6_Offed.State, s_7_Deteling.State, s_8_Deleted.State} { if node == state { return true } } return false }
package workflow import ( "time" "github.com/google/uuid" "github.com/pkg/errors" "github.com/yamil-rivera/flowit/internal/config" ) // Workflow is the data structure representing a single workflow instance type Workflow struct { ID string Preffix string Name string IsActive bool Executions []Execution LatestExecution *Execution // TODO: Switch to pointer and refer to a separate struct in the repository // This to avoid several workflows based on the same config to have duplicated data in the repo State config.Flowit Metadata WorkflowMetadata } // WorkflowMetadata is the data structure that provides workflow instance metadata type WorkflowMetadata struct { Version uint64 Started uint64 Updated uint64 Finished uint64 } // Execution is the data structure representing a single execution instance type Execution struct { ID string FromStage string Stage string Args []string Checkpoint int Failed bool Metadata ExecutionMetadata } // ExecutionMetadata is the data structure that provides execution instance metadata type ExecutionMetadata struct { Version uint64 Started uint64 Finished uint64 } // OptionalWorkflow is the data type that wraps an Workflow in an optional type OptionalWorkflow struct { workflow Workflow isSet bool } // WorkflowState defines all the possible workflow states type WorkflowState int const ( STARTED WorkflowState = iota FAILED WorkflowState = iota FINISHED WorkflowState = iota ) // Service implements the Workflow Service methods type Service struct{} // NewService builds a new Workflow Service func NewService() *Service { return &Service{} } // CreateWorkflow creates a new Workflow with a name and a variable map as inputs func (s *Service) CreateWorkflow(workflowName string, definition config.Flowit) *Workflow { workflowID := uuid.New().String() return &Workflow{ ID: workflowID, Preffix: workflowID[:6], Name: workflowName, IsActive: false, State: definition, Metadata: WorkflowMetadata{ Version: 0, }, } } // CancelWorkflow marks workflow as cancelled // TODO: Unit test func (s *Service) CancelWorkflow(w *Workflow) { now := uint64(time.Now().UnixNano()) w.IsActive = false w.Metadata.Updated = now w.Metadata.Finished = now } // StartExecution returns a new Execution for a given Workflow func (s *Service) StartExecution(workflow *Workflow, fromStage, currentStage string, args []string) *Execution { now := uint64(time.Now().UnixNano()) execution := Execution{ ID: uuid.New().String(), FromStage: fromStage, Stage: currentStage, Args: args, Checkpoint: -1, Metadata: ExecutionMetadata{ Version: 0, Started: now, }, } workflow.IsActive = true workflow.Executions = append([]Execution{execution}, workflow.Executions...) workflow.LatestExecution = &execution if workflow.Metadata.Started == 0 { workflow.Metadata.Started = now } workflow.Metadata.Updated = now return &execution } // SetCheckpoint sets the checkpoint for a given execution func (s *Service) SetCheckpoint(execution *Execution, checkpoint int) { execution.Checkpoint = checkpoint } // FinishExecution marks a given execution as finished func (s *Service) FinishExecution(workflow *Workflow, execution *Execution, workflowState WorkflowState) error { if execution.Metadata.Finished > 0 { return errors.New("Execution has already finished") } now := uint64(time.Now().UnixNano()) execution.Metadata.Finished = now if workflowState == FAILED { execution.Failed = true execution.Stage = execution.FromStage } workflow.IsActive = workflowState != FINISHED workflow.Metadata.Updated = now if workflowState == FINISHED { workflow.Metadata.Finished = now } return nil } // AddVariables adds the given variables to the workflow instance func (s *Service) AddVariables(workflow *Workflow, variables map[string]interface{}) { for k, v := range variables { workflow.State.Variables[k] = v } } // NewWorkflowOptional receives a Workflow and returns a filled optional ready to be unwrapped func NewWorkflowOptional(workflow Workflow) OptionalWorkflow { return OptionalWorkflow{ workflow: workflow, isSet: true, } } // Get works on a pointer to OptionalWorkflow and returns the Workflow wrapped in the optional or // returns an error in case the optional is empty func (optional *OptionalWorkflow) Get() (Workflow, error) { if !optional.isSet { return optional.workflow, errors.New("optional value is not set") } return optional.workflow, nil } // Stage returns the flowit configuration stage given a stage ID func (w Workflow) Stage(stageID string) config.Stage { for _, wf := range w.State.Workflows { if wf.ID != w.Name { continue } for _, s := range wf.Stages { if s.ID == stageID { return s } } } return config.Stage{} } // StateMachineID returns the worklow state machine ID func (w Workflow) StateMachineID() string { for _, wf := range w.State.Workflows { if w.Name == wf.ID { return wf.StateMachine } } return "" }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //530. Minimum Absolute Difference in BST //Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. //Example: //Input: // 1 // \ // 3 // / // 2 //Output: //1 //Explanation: //The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). //Note: There are at least two nodes in this BST. ///** // * Definition for a binary tree node. // * type TreeNode struct { // * Val int // * Left *TreeNode // * Right *TreeNode // * } // */ //func getMinimumDifference(root *TreeNode) int { //} // Time Is Money
package handler import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" "proxy_download/model" "strconv" ) func GroupDetail(context *gin.Context) { var group model.Group idString := context.Param("id") id, _ := strconv.Atoi(idString) groupDetail, err := group.Detail(id) if err != nil { fmt.Println("query table group err = ", err) return } context.JSON(http.StatusOK, gin.H{"list": groupDetail}) } func GroupEdit(context *gin.Context) { var group model.Group if err := context.ShouldBind(&group); err != nil { context.JSON(http.StatusOK, gin.H{"err": "输入的数据不合法"}) log.Panicln("err ->", err.Error()) return } if group.ID != 0 { err := group.Update() if err != nil { fmt.Println("update group err = ", err) context.JSON(http.StatusBadRequest, gin.H{"err": "update group err" + err.Error()}) return } context.JSON(http.StatusOK, gin.H{"msg": "update group success"}) return } id, err := group.Save() if err != nil { fmt.Println("save group err ", err) context.JSON(http.StatusBadRequest, gin.H{"err": "save group err" + err.Error()}) return } context.JSON(http.StatusOK, gin.H{"msg": "save group success, id:" + strconv.FormatInt(id, 10)}) } func GroupList(context *gin.Context) { var group model.Group page, err := strconv.Atoi(context.DefaultQuery("page", "1")) pagesize, err := strconv.Atoi(context.DefaultQuery("pagesize", "10")) fmt.Println("page ") groups, count, err := group.List(page, pagesize) if err != nil { err := fmt.Errorf("query table group err = %v", err.Error()) fmt.Println(err) context.JSON(http.StatusBadGateway, err) return } context.JSON(http.StatusOK, gin.H{"list": groups, "count": count}) } func GroupDel(context *gin.Context) { var groups NullMap var group model.Group err := context.BindJSON(&groups) if err != nil { log.Println("json.Unmarshal err = ", err) context.JSON(http.StatusOK, gin.H{"err": "get ids error"}) return } switch ids := groups["ids"].(type) { // 对返回的元素进行判断 float64 id []interface{} ids case float64: if err = group.Delete(ids); err != nil { fmt.Println("delete group err :", err) context.JSON(http.StatusBadRequest, gin.H{"err": err}) return } context.JSON(http.StatusOK, gin.H{"msg": "del success"}) return case []interface{}: if err = group.Deletes(ids); err != nil { fmt.Println("list delete group err :", err) context.JSON(http.StatusBadRequest, gin.H{"err": err}) return } context.JSON(http.StatusOK, gin.H{"msg": "del list success"}) } } func GroupNameValidate(context *gin.Context) { result, err := NameValidate(context, "groups") if err != nil { fmt.Println("err = ", err) context.JSON(http.StatusBadRequest, Data{"err": err.Error()}) return } context.JSON(http.StatusOK, result) }
package gouldian_test import ( "testing" µ "github.com/fogfish/gouldian/v2" "github.com/fogfish/gouldian/v2/mock" "github.com/fogfish/it" ) func TestJWTLit(t *testing.T) { foo := mock.Endpoint( µ.GET( µ.URI(), µ.JWT(µ.Token.Sub, "sub"), ), ) success := mock.Input(mock.JWT(µ.Token{"sub": "sub"})) failure1 := mock.Input(mock.JWT(µ.Token{"sub": "foo"})) failure2 := mock.Input() it.Ok(t). If(foo(success)).Should().Equal(nil). If(foo(failure1)).ShouldNot().Equal(nil). If(foo(failure2)).ShouldNot().Equal(nil) } func TestJWTVar(t *testing.T) { type MyT struct{ Sub string } sub := µ.Optics1[MyT, string]() foo := mock.Endpoint( µ.GET( µ.URI(), µ.JWT(µ.Token.Sub, sub), ), ) t.Run("some", func(t *testing.T) { var val MyT req := mock.Input(mock.JWT(µ.Token{"sub": "sub"})) it.Ok(t). If(foo(req)).Should().Equal(nil). If(µ.FromContext(req, &val)).Should().Equal(nil). If(val.Sub).Should().Equal("sub") }) t.Run("none", func(t *testing.T) { req := mock.Input() it.Ok(t). If(foo(req)).ShouldNot().Equal(nil) }) } func TestJWTOneOf(t *testing.T) { foo := mock.Endpoint( µ.GET( µ.URI(), µ.JWTOneOf(µ.Token.Scope, "a", "b", "c"), ), ) success := mock.Input(mock.JWT(µ.Token{"scope": "x y c"})) failure1 := mock.Input(mock.JWT(µ.Token{"scope": "x y"})) failure2 := mock.Input() it.Ok(t). If(foo(success)).Should().Equal(nil). If(foo(failure1)).ShouldNot().Equal(nil). If(foo(failure2)).ShouldNot().Equal(nil) } func TestJWTAllOf(t *testing.T) { foo := mock.Endpoint( µ.GET( µ.URI(), µ.JWTAllOf(µ.Token.Scope, "a", "b", "c"), ), ) success := mock.Input(mock.JWT(µ.Token{"scope": "a b c"})) failure1 := mock.Input(mock.JWT(µ.Token{"scope": "a b"})) failure2 := mock.Input() it.Ok(t). If(foo(success)).Should().Equal(nil). If(foo(failure1)).ShouldNot().Equal(nil). If(foo(failure2)).ShouldNot().Equal(nil) } func TestJWTMaybe(t *testing.T) { type MyT struct{ Sub string } sub := µ.Optics1[MyT, string]() foo := mock.Endpoint( µ.GET( µ.URI(), µ.JWTMaybe(µ.Token.Sub, sub), ), ) t.Run("some", func(t *testing.T) { var val MyT req := mock.Input(mock.JWT(µ.Token{"sub": "sub"})) it.Ok(t). If(foo(req)).Should().Equal(nil). If(µ.FromContext(req, &val)).Should().Equal(nil). If(val.Sub).Should().Equal("sub") }) t.Run("empty", func(t *testing.T) { var val MyT req := mock.Input(mock.JWT(µ.Token{})) it.Ok(t). If(foo(req)).Should().Equal(nil). If(µ.FromContext(req, &val)).Should().Equal(nil). If(val.Sub).Should().Equal("") }) t.Run("none", func(t *testing.T) { req := mock.Input() it.Ok(t). If(foo(req)).ShouldNot().Equal(nil) }) }
package model type Result struct { Status int64 Msg string Data interface{} } type VersionResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data Version `json:"data" description:"版本信息"` } type VersionListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Total int `json:"total"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []Version `json:"data" description:"版本日志列表"` } type JpushMsgListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Total int `json:"total"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []JpushMessage `json:"data" description:"交易消息列表"` } type SysMsgListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Total int `json:"total"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []SysMessage `json:"data" description:"系统消息列表"` } type SysMsgResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data *SysMessage `json:"data" description:"系统消息"` } type TokenInfoResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data *Token `json:"data" description:"token信息"` } type TokenListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []Token `json:"data" description:"token列表"` } type VestingListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []Vesting `json:"data" description:"股权信息列表"` } type ReturnListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []VestingItem `json:"data" description:"返还记录列表"` } type TransResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data *Transaction `json:"data" description:"交易信息"` } type StatisticsInfo struct { OutAmount int `json:"outAmount" description:"转出"` InAmount int `json:"inAmount" description:"转入"` } type TransStatisticsResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Data StatisticsInfo `json:"data" description:"统计信息"` Msg string `json:"msg" description:"status为false时的错误信息"` } type TransListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Total int `json:"total" description:"交易总数"` Data []Transaction `json:"data" description:"交易列表"` Msg string `json:"msg" description:"status为false时的错误信息"` } type JpushMsgResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data *JpushMessage `json:"data" description:"交易消息"` } type JsonResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data string `json:"data" description:"结果"` } type ConfirmItem struct { ConfirmCount int `json:"confirmCount" description:"已签名的次数"` Threshold int `json:"threshold" description:"需签名的次数"` } type ConfirmResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data ConfirmItem `json:"data" description:"签名情况"` } //合约调用返回结果 type CCInvokeResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` TxId string `json:"txId" description:"交易ID"` TokenId string `json:"tokenId" description:"token标识"` ContractAddress string `json:"contractAddress" description:"合约地址"` } type SignInfoResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data *SignData `json:"data" description:"签名数据"` } type SignListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Total int `json:"total"` Data []SignData `json:"data" description:"签名记录"` } type QuestionResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data Question `json:"data" description:"意见反馈信息"` } type QuestionListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []Question `json:"data" description:"意见反馈列表"` } type ContactResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data Contact `json:"data" description:"联系人信息"` } type ContactListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []Contact `json:"data" description:"联系人列表"` } type ReturnGasConfigResponse struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data ReturnGasConfig `json:"data" description:"数据信息"` } type ReturnGasConfig struct { InitReleaseRatio string `json:"initReleaseRatio" description:"立即返还比例(按百分比)"` Interval string `json:"interval" description:"每次释放间隔时间以秒为单位"` ReleaseRatio string `json:"releaseRatio" description:"释放比例(按百分比)"` } type ContractResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data *Contract `json:"data" description:"合约信息"` } type ContractListResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data []Contract `json:"data" description:"合约列表"` }
package main import ( "context" "encoding/base64" "flag" "io/ioutil" "os" "os/signal" "syscall" "time" //"github.com/gtfierro/xboswave/ingester/types" "github.com/immesys/wavemq/mqpb" logrus "github.com/sirupsen/logrus" "google.golang.org/grpc" ) func init() { logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true, ForceColors: true}) logrus.SetOutput(os.Stdout) logrus.SetLevel(logrus.DebugLevel) } // This is an example that shows how to publish and subscribe to a WAVEMQ site router // Fill these fields in: const EntityFile = "wavemqingester.ent" const Namespace = "GyAlyQyfJuai4MCyg6Rx9KkxnZZXWyDaIo0EXGY9-WEq6w==" const SiteRouter = "127.0.0.1:4516" var configfile = flag.String("config", "ingester.yml", "Path to ingester.yml file") var IngesterName = "testingester3" var IngestSubscriptionExpiry = int64(48 * 60 * 60) // 48 hours var MaxInMemoryTimeseriesBuffer = 1000 // # of time/reading pairs var TimeseriesOperationTimeout = 1 * time.Minute var namespaceBytes []byte func main() { flag.Parse() cfg, err := ReadConfig(*configfile) if err != nil { logrus.Fatal(err) } DrawConfig(cfg) ctx := context.Background() namespaceBytes, err = base64.URLEncoding.DecodeString(Namespace) if err != nil { logrus.Fatalf("failed to decode namespace: %v", err) } // Establish a GRPC connection to the site router. conn, err := grpc.DialContext(ctx, cfg.WAVEMQ.SiteRouter, grpc.WithInsecure(), grpc.FailOnNonTempDialError(true), grpc.WithBlock()) if err != nil { logrus.Fatalf("Could not connect to site router %v", err) } // Create the WAVEMQ client client := mqpb.NewWAVEMQClient(conn) // setup kill interruptSignal := make(chan os.Signal, 1) done := make(chan struct{}) signal.Notify(interruptSignal, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) go func() { killSignal := <-interruptSignal switch killSignal { case os.Interrupt, syscall.SIGINT: logrus.Warning("Caught SIGINT; closing...") case syscall.SIGTERM: logrus.Warning("Caught SIGTERM; closing...") default: logrus.Warning(killSignal) } conn.Close() close(done) }() // config manager cfgmgr, err := NewCfgManager(cfg) if err != nil { logrus.Fatalf("Could not open config manager (%v)", err) } // Load the WAVE3 entity that will be used perspective, err := ioutil.ReadFile(cfg.WAVEMQ.EntityFile) if err != nil { logrus.Fatalf("could not load entity (%v) you might need to create one and grant it permissions\n", err) } persp := &mqpb.Perspective{ EntitySecret: &mqpb.EntitySecret{ DER: perspective, }, } ingest := NewIngester(client, persp, *cfg, cfgmgr, ctx) <-done logrus.Info(ingest.Finish()) }
package proxy import ( "log" "net/http" _ "net/http/pprof" "runtime" "time" ) func GoroNum(n int) { go func() { for _ = range time.Tick(time.Duration(n) * time.Second) { log.Println("#goroutines", runtime.NumGoroutine()) } }() } func PProfRun(addr string) { go func() { log.Println(http.ListenAndServe(addr, nil)) }() }
package store import ( "io" "mime/multipart" "os" "path/filepath" ) // Service is an interface that defines actions for storing files type Service interface { SaveFile(fileName string, file multipart.File) error } type serviceImpl struct { uploadDir string } // NewService creates new service for storing files func NewService(uploadDir string) *serviceImpl { return &serviceImpl{ uploadDir: uploadDir, } } // SaveFile saves file in path func (s *serviceImpl) SaveFile(fileName string, file multipart.File) error { filePath := filepath.Join(s.uploadDir, fileName) f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { return err } defer f.Close() io.Copy(f, file) return nil }
package service import ( "MI/models" "MI/pkg/cache" "MI/pkg/logger" "MI/utils/common" "MI/utils/response" "context" "fmt" "github.com/gin-gonic/gin" "strconv" ) func AddCart(c *gin.Context ,item models.Item){ cacheKey := fmt.Sprintf("cart:user:%s",item.Uid) //判断 cart:key在redis中是否已存在,商品不存在,新增该购物车,商品存在,商品数量+1 if has := cache.HashIsExists(context.Background(),cacheKey,item.Pid);!has{ //将cart插入到redis var data = map[string]interface{}{ item.Pid:item.Num, } if err := cache.HashHSet(context.Background(),cacheKey,data);err != nil { logger.Logger.Error(err) response.RespError(c,"添加失败") return } }else{ if err := addNum(cacheKey,item.Pid,1);err != nil { logger.Logger.Error(err) response.RespError(c,"添加失败") return } } response.RespSuccess(c,"添加成功") } func CartList(c *gin.Context,uid string){ cacheKey := fmt.Sprintf("cart:user:%s",uid) //根据key 获取当前用户下购物车的商品数据 resp,err := cache.HashAll(context.Background(),cacheKey) if err != nil { logger.Logger.Error(err) response.RespError(c,err) return } //生成购物车唯一主键 id := common.GenerateSnowId() var cart models.Cart var totalPrice float64 //resp map[商品id]商品数量 for i, v := range resp { var cartItem = models.CartItem{} pid,_ := strconv.Atoi(i) num,_ := strconv.ParseFloat(v,64) //根据商品id查询商品详情 product, err := models.GetProductByWhere("id=?", pid) if err != nil { logger.Logger.Error(err) response.RespError(c,"购物车商品不存在") return } cartItem.Cid = id cartItem.Product =product cartItem.Num, _ =strconv.Atoi(v) cart.CartItem =append(cart.CartItem,cartItem) totalPrice += num * product.ShopPrice } cart.Uid,_ =strconv.Atoi(uid) cart.Id = id response.RespData(c,"ok",cart) } func CartUpdateNum(c *gin.Context,item models.Item){ cacheKey := fmt.Sprintf("cart:user:%s",item.Uid) //更新redis 对应 购物车中 商品的数量 if has := cache.HashIsExists(context.Background(),cacheKey,item.Pid);!has { response.RespError(c,"商品不存在") return } var data = map[string]interface{}{ item.Pid: item.Num, } if err := cache.HashHSet(context.Background(), cacheKey, data); err != nil { logger.Logger.Error(err) response.RespError(c, "更新失败") return } response.RespSuccess(c,"更新成功") } func DeleteCart(c *gin.Context,uid,pid string){ cacheKey := fmt.Sprintf("cart:user:%s",uid) if has := cache.HashIsExists(context.Background(),cacheKey,pid);!has { response.RespError(c,"商品不存在") return } if err := cache.HashDel(context.Background(),cacheKey,pid);err != nil{ response.RespError(c,"删除失败") return } response.RespSuccess(c,"删除成功") } func addNum(key,filed string,count int64)error{ return cache.HashIncrBy(context.Background(),key,filed,count) }
package engine import ( "context" "sync" "time" "code.cloudfoundry.org/lager" "code.cloudfoundry.org/lager/lagerctx" "github.com/concourse/concourse/atc" "github.com/concourse/concourse/atc/db" "github.com/concourse/concourse/atc/exec" "github.com/concourse/concourse/atc/metric" ) //go:generate counterfeiter . Engine type Engine interface { LookupBuild(lager.Logger, db.Build) Build ReleaseAll(lager.Logger) } //go:generate counterfeiter . Build type Build interface { Resume(lager.Logger) } //go:generate counterfeiter . StepBuilder type StepBuilder interface { BuildStep(db.Build) (exec.Step, error) } func NewEngine(builder StepBuilder) Engine { return &engine{ builder: builder, release: make(chan bool), trackedStates: new(sync.Map), waitGroup: new(sync.WaitGroup), } } type engine struct { builder StepBuilder release chan bool trackedStates *sync.Map waitGroup *sync.WaitGroup } func (engine *engine) LookupBuild(logger lager.Logger, build db.Build) Build { ctx, cancel := context.WithCancel(context.Background()) return NewBuild( ctx, cancel, build, engine.builder, engine.release, engine.trackedStates, engine.waitGroup, ) } func (engine *engine) ReleaseAll(logger lager.Logger) { logger.Info("calling-release-on-builds") close(engine.release) logger.Info("waiting-on-builds") engine.waitGroup.Wait() logger.Info("finished-waiting-on-builds") } func NewBuild( ctx context.Context, cancel func(), build db.Build, builder StepBuilder, release chan bool, trackedStates *sync.Map, waitGroup *sync.WaitGroup, ) Build { return &execBuild{ ctx: ctx, cancel: cancel, build: build, builder: builder, release: release, trackedStates: trackedStates, waitGroup: waitGroup, } } type execBuild struct { ctx context.Context cancel func() build db.Build builder StepBuilder release chan bool trackedStates *sync.Map waitGroup *sync.WaitGroup } func (build *execBuild) Resume(logger lager.Logger) { build.waitGroup.Add(1) defer build.waitGroup.Done() logger = logger.WithData(lager.Data{ "build": build.build.ID(), "pipeline": build.build.PipelineName(), "job": build.build.JobName(), }) lock, acquired, err := build.build.AcquireTrackingLock(logger, time.Minute) if err != nil { logger.Error("failed-to-get-lock", err) return } if !acquired { logger.Debug("build-already-tracked") return } defer lock.Release() found, err := build.build.Reload() if err != nil { logger.Error("failed-to-load-build-from-db", err) return } if !found { logger.Info("build-not-found") return } if !build.build.IsRunning() { logger.Info("build-already-finished") return } notifier, err := build.build.AbortNotifier() if err != nil { logger.Error("failed-to-listen-for-aborts", err) return } defer notifier.Close() step, err := build.builder.BuildStep(build.build) if err != nil { logger.Error("failed-to-build-step", err) return } build.trackStarted(logger) defer build.trackFinished(logger) logger.Info("running") state := build.runState() defer build.clearRunState() noleak := make(chan bool) defer close(noleak) go func() { select { case <-noleak: case <-notifier.Notify(): logger.Info("aborting") build.cancel() } }() done := make(chan error) go func() { ctx := lagerctx.NewContext(build.ctx, logger) done <- step.Run(ctx, state) }() select { case <-build.release: logger.Info("releasing") case err = <-done: build.finish(logger.Session("finish"), err, step.Succeeded()) } } func (build *execBuild) finish(logger lager.Logger, err error, succeeded bool) { if err == context.Canceled { build.saveStatus(logger, atc.StatusAborted) logger.Info("aborted") } else if err != nil { build.saveStatus(logger, atc.StatusErrored) logger.Info("errored", lager.Data{"error": err.Error()}) } else if succeeded { build.saveStatus(logger, atc.StatusSucceeded) logger.Info("succeeded") } else { build.saveStatus(logger, atc.StatusFailed) logger.Info("failed") } } func (build *execBuild) saveStatus(logger lager.Logger, status atc.BuildStatus) { if err := build.build.Finish(db.BuildStatus(status)); err != nil { logger.Error("failed-to-finish-build", err) } } func (build *execBuild) trackStarted(logger lager.Logger) { metric.BuildStarted{ PipelineName: build.build.PipelineName(), JobName: build.build.JobName(), BuildName: build.build.Name(), BuildID: build.build.ID(), TeamName: build.build.TeamName(), }.Emit(logger) } func (build *execBuild) trackFinished(logger lager.Logger) { found, err := build.build.Reload() if err != nil { logger.Error("failed-to-load-build-from-db", err) return } if !found { logger.Info("build-removed") return } if !build.build.IsRunning() { metric.BuildFinished{ PipelineName: build.build.PipelineName(), JobName: build.build.JobName(), BuildName: build.build.Name(), BuildID: build.build.ID(), BuildStatus: build.build.Status(), BuildDuration: build.build.EndTime().Sub(build.build.StartTime()), TeamName: build.build.TeamName(), }.Emit(logger) } } func (build *execBuild) runState() exec.RunState { existingState, _ := build.trackedStates.LoadOrStore(build.build.ID(), exec.NewRunState()) return existingState.(exec.RunState) } func (build *execBuild) clearRunState() { build.trackedStates.Delete(build.build.ID()) }
package main import "fmt" import "time" //365.2545 // 2456668.43767 //The reference time used in the layouts is: //Mon Jan 2 15:04:05 MST 2006 //which is Unix time 1136239445. //calculate the Julian date, provided it's within 209 years of Jan 2, 2006. func Julian(t time.Time) float64 { // Julian date, in seconds, of the "Format" standard time. // (See http://www.onlineconversion.com/julian_date.htm) const julian = 2453738.4195 // Easiest way to get the time.Time of the Unix time. // (See comments for the UnixDate in package Time.) unix := time.Unix(1136239445, 0) const oneDay = float64(86400. * time.Second) return julian + float64(t.Sub(unix))/oneDay } const ( dateFmt = "20060102" ) // round value - convert to int64 func Round(value float64) int64 { if value < 0.0 { value -= 0.5 } else { value += 0.5 } return int64(value) } func main() { //tToday := time.Now() //tToday p := tToday 0.UTC().Format(dateFmt) //t0, _ := time.ParseInLocation(dateFmt, tToday p, time.UTC) tToday, _ := time.ParseInLocation(dateFmt, "20140101", time.UTC) t1, _ := time.ParseInLocation(dateFmt, "20120401", time.UTC) fmt.Printf("Today %s\n", tToday.Format(dateFmt)) fmt.Printf("Yesterday %s\n", t1.Format(dateFmt)) // today t0j := Julian(tToday) fmt.Printf("Julian date:%f\n", t0j) //yesterday t1j := Julian(t1) fmt.Printf("Julian date:%f\n", t1j) t := t0j - t1j fmt.Printf("days since:%f\n", t) // 366.000000 d := t/365.2545 fmt.Printf("years precise:%f\n", d) y := Round(t/365.2545) // years since:1 fmt.Printf("full years since:%d\n", y) d = t/365.2545 fmt.Printf("+days:%f\n", d) if d > 0 { } }
package parser import ( "github.com/Spriithy/BPL/compiler/token" "github.com/Spriithy/BPL/compiler/ast" "fmt" "os" ) var prOps = map[string]struct { prec int rAssoc bool }{ "++" : {50, false}, "--" : {50, false}, "." : {40, false}, "[" : {40, false}, "!" : {30, true}, "~" : {30, true}, "-u" : {29, true}, "--u" : {29, true}, "++u": {29, true}, "**" : {28, true}, "*" : {27, false}, "/" : {27, false}, "%" : {27, false}, "+" : {26, false}, "-" : {26, false}, ">>" : {25, false}, "<<" : {25, false}, ">" : {24, false}, ">=" : {24, false}, "<" : {24, false}, "<=" : {24, false}, "==" : {23, false}, "!=" : {23, false}, "&" : {22, false}, "^" : {21, false}, "|" : {20, false}, "&&" : {19, false}, "||" : {18, false}, "=" : {10, true}, "+=" : {10, true}, "-=" : {10, true}, "*=" : {10, true}, "/=" : {10, true}, "**=" : {10, true}, "^=" : {10, true}, "~=" : {10, true}, "|=" : {10, true}, "&=" : {10, true}, "%=" : {10, true}, "<<=" : {10, true}, ">>=": {10, true}, "," : {9, false}, } type parser struct { path, src string lno int tokens token.TQueue } func Parser(path, source string, tokens token.TQueue) *parser { p := new(parser) p.path = path p.src = source p.tokens = tokens p.lno = p.tokens.PeekHead().Lno return p } func (p *parser) errorf(format string, a ...interface{}) { fmt.Printf("%s#%d: ", p.path, p.lno) fmt.Printf(format + "\n", a ...) os.Exit(1) } func (p *parser) warningf(format string, a... interface{}) { fmt.Printf("%s#%d: ", p.path, p.lno) fmt.Printf(format + "\n", a ...) } func (p *parser) logf(format string, a... interface{}) { fmt.Printf(format + "\n", a ...) } func (p *parser) Parse() { r := p.sya(p.tokens) println(r.String()) } /* Shunting Yard Implementation to parse Expressions ------------------------------------------------- While there are tokens to be read: Read a token. If the token is a number, then push it to the output queue. If the token is a function token, then push it onto the stack. If the token is a function argument separator (e.g., a comma): Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. (* If no left parentheses are encountered, either the separator was misplaced or parentheses were mismatched. *) If the token is an operator, o1, then: while there is an operator token o2, at the top of the operator stack and either o1 is left-associative and its precedence is less than or equal to that of o2, or o1 is right associative, and has precedence less than that of o2, pop o2 off the operator stack, onto the output queue; at the end of iteration push o1 onto the operator stack. If the token is a left parenthesis (i.e. "("), then push it onto the stack. If the token is a right parenthesis (i.e. ")"): Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. Pop the left parenthesis from the stack, but not onto the output queue. If the token at the top of the stack is a function token, pop it onto the output queue. If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. When there are no more tokens to read: While there are still operator tokens in the stack: If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. Pop the operator onto the output queue. Exit. */ func (p *parser) sya(input token.TQueue) *ast.Node { var operands ast.NStack var operators *token.TStack operands = make(ast.NStack, 0) operators = token.TokenStack() for tok := input.Dequeue(); tok.Sym != "EOF"; tok = input.Dequeue() { switch tok.Kind { case "LParen": operators.Push(tok) case "RParen": for { // pop item ("(" or operator) from stack if operators.Empty() { p.errorf("Unmatched parenthesis on line %d, expected '(' to match closing parenthesis in expression", p.lno) } op := operators.Pop() if op.Sym == "(" { break // discard "(" } if isUnary(op.Sym) { node := ast.MakeNode(*op) node.AddChild(operands.Pop()) operands.Push(node) break } RHS := operands.Pop() LHS := operands.Pop() operands.Push(ast.MakeParentNode(*op, RHS, LHS)) } case "Semicolon": // drain stack to temporary result for !operators.Empty() { if operators.PeekTop().Sym == "(" { p.errorf("Unmatched parenthesis on line %d, expected ')' to match previous parenthesis in expression", p.lno) } RHS := operands.Pop() LHS := operands.Pop() operands.Push(ast.MakeParentNode(*operators.Pop(), RHS, LHS)) } case "--------------" /* NewLine */ : // drain stack to temporary result for !operators.Empty() { if operators.PeekTop().Sym == "(" { p.errorf("Unmatched parenthesis on line %d, expected ')' to match previous parenthesis in expression", p.lno) } RHS := operands.Pop() LHS := operands.Pop() operands.Push(ast.MakeParentNode(*operators.Pop(), RHS, LHS)) } default: if o1, isOp := prOps[tok.Sym]; isOp { // token is an operator for !operators.Empty() { // consider top item on stack op := operators.PeekTop() if o2, isOp := prOps[op.Sym]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } // top item is an operator that needs to come off op = operators.Pop() if isUnary(op.Sym) { node := ast.MakeNode(*op) node.AddChild(operands.Pop()) operands.Push(node) break } RHS := operands.Pop() LHS := operands.Pop() operands.Push(ast.MakeParentNode(*op, RHS, LHS)) } // push operator (the new one) to stack operators.Push(tok) } else { operands.Push(ast.MakeNode(*tok)) } } } // drain stack to result for !operators.Empty() { if operators.PeekTop().Sym == "(" { p.errorf("Unmatched parenthesis on line %d, expected ')' to match previous parenthesis in expression", p.lno) } RHS := operands.Pop() LHS := operands.Pop() operands.Push(ast.MakeParentNode(*operators.Pop(), RHS, LHS)) } result := operands.Pop() for !operands.Empty() { result.AddSibling(operands.Pop()) } return result } func isUnary(op string) bool { return op == "-u" || op == "!" || op == "++" || op == "--" || op == "++u" || op == "--u" }
package main import ( "sync" "time" ) var rwMu sync.RWMutex var count int // 死锁 //func main() { // // go StartHttpDebuger() // go RWA() // time.Sleep(2 * time.Second) // rwMu.Lock() // defer rwMu.Unlock() // count++ // fmt.Println(count) //} func RWA() { rwMu.RLock() defer rwMu.Unlock() RWB() } func RWB() { time.Sleep(time.Second * 5) RWC() } func RWC() { rwMu.RLock() defer rwMu.Unlock() }
package main import ( "fmt" "os" "github.com/isutare412/torbula" ) func main() { if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "usage: %s [setting.ini]\n", os.Args[0]) os.Exit(1) } var server *torbula.Server server, err := torbula.NewServer(os.Args[1]) if err != nil { fmt.Fprintf(os.Stderr, "on NewServer: %v\n", err) os.Exit(1) } if err := server.Run(); err != nil { fmt.Fprintf(os.Stderr, "server stopped: %v\n", err) os.Exit(1) } }
/* Usando uma literal composta: Crie um array que suporte 5 valores to tipo int Atribua valores aos seus índices Utilize range e demonstre os valores do array. Utilizando format printing, demonstre o tipo do array. */ package main import ( "fmt" ) func main() { listaDeInteiros := [5]int{ 1, 2, 3, 4, 5} fmt.Println(listaDeInteiros) for indice, valor := range listaDeInteiros { fmt.Printf("Índice: %v - Valor: %v\n", indice, valor) } fmt.Printf("Tipo do meu array: %T\n", listaDeInteiros) }
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file contains the implementation of the resource that manages the collection of // projects. package eawx import ( "fmt" "github.com/golang/glog" "github.com/lz006/extended-awx-client-go/eawx/internal/data" yaml "gopkg.in/yaml.v2" ) type GroupsResource struct { Resource } func NewGroupsResource(connection *Connection, path string) *GroupsResource { resource := new(GroupsResource) resource.connection = connection resource.path = path return resource } func (r *GroupsResource) Get() *GroupsGetRequest { request := new(GroupsGetRequest) request.resource = &r.Resource return request } func (r *GroupsResource) Id(id int) *GroupResource { return NewGroupResource(r.connection, fmt.Sprintf("%s/%d", r.path, id)) } type GroupsGetRequest struct { Request } func (r *GroupsGetRequest) Filter(name string, value interface{}) *GroupsGetRequest { r.addFilter(name, value) return r } func (r *GroupsGetRequest) Send() (response *GroupsGetResponse, err error) { output := new(data.GroupsGetResponse) err = r.get(output) if err != nil { return } response = new(GroupsGetResponse) response.count = output.Count response.previous = output.Previous response.next = output.Next response.results = make([]*Group, len(output.Results)) for i := 0; i < len(output.Results); i++ { response.results[i] = new(Group) response.results[i].id = output.Results[i].Id response.results[i].name = output.Results[i].Name var vars *data.Variables err = yaml.Unmarshal([]byte(output.Results[i].Vars), &vars) if err != nil { glog.Warningf("Error parsing: %v", err) } if vars != nil { var endpoints []*Endpoint for _, endpoint := range vars.Endpoints { tmpEndpoint := &Endpoint{ endpoint: endpoint.Endpoint, bearerTokenFile: endpoint.BearerTokenFile, port: endpoint.Port, portName: endpoint.PortName, protocol: endpoint.Protocol, scheme: endpoint.Scheme, targetPort: endpoint.TargetPort, honorLabels: endpoint.HonorLabels, interval: endpoint.Interval, scrapeTimeout: endpoint.ScrapeTimeout, } if &endpoint.TLSConf != nil { tmpTLSConfig := &TLSConfig{ caFile: endpoint.TLSConf.CAFile, hostname: endpoint.TLSConf.Hostname, insecureSkipVerify: endpoint.TLSConf.InsecureSkipVerify, } tmpEndpoint.tlsConf = tmpTLSConfig } endpoints = append(endpoints, tmpEndpoint) } response.results[i].vars = &Variables{ mType: vars.Type, endpoints: endpoints, } } } return } type GroupsGetResponse struct { ListGetResponse results []*Group } func (r *GroupsGetResponse) Results() []*Group { return r.results }
package config import ( "os" "os/signal" "syscall" ) // WaitSIGHUP blocks until a SIGHUP signal is received. func WaitSIGHUP() { ch := make(chan os.Signal, 1) signal.Notify(ch, os.Signal(syscall.SIGHUP)) <-ch }
package ldap import ( "log" "strings" "github.com/liut/staffio/pkg/models" ) var ( _ models.Authenticator = (*LDAPStore)(nil) _ models.StaffStore = (*LDAPStore)(nil) _ models.PasswordStore = (*LDAPStore)(nil) _ models.GroupStore = (*LDAPStore)(nil) ) type LDAPStore struct { sources []*ldapSource pageSize int } func NewStore(cfg *Config) (*LDAPStore, error) { store := &LDAPStore{ pageSize: 100, } for _, addr := range strings.Split(cfg.Addr, ",") { c := &Config{ Addr: addr, Base: cfg.Base, Bind: cfg.Bind, Passwd: cfg.Passwd, } ls, err := NewSource(c) if err != nil { return nil, err } store.sources = append(store.sources, ls) } return store, nil } func (s *LDAPStore) Authenticate(uid, passwd string) (err error) { for _, ls := range s.sources { dn := ls.UDN(uid) err = ls.Bind(dn, passwd, true) if err == nil { debug("authenticate(%s,****) ok", uid) return } } log.Printf("Authen failed for %s, reason: %s", uid, err) return } func (s *LDAPStore) Get(uid string) (staff *models.Staff, err error) { // log.Printf("sources %s", ldapSources) for _, ls := range s.sources { staff, err = ls.GetStaff(uid) if err == nil { return } else { log.Printf("GetStaff %s ERR %s", uid, err) } } err = ErrNotFound return } func (s *LDAPStore) All() (staffs models.Staffs) { for _, ls := range s.sources { staffs = ls.ListPaged(s.pageSize) if len(staffs) > 0 { return } } return } func (s *LDAPStore) Save(staff *models.Staff) (isNew bool, err error) { for _, ls := range s.sources { isNew, err = ls.storeStaff(staff) if err != nil { log.Printf("storeStaff at %s ERR: %s", ls.Addr, err) return } } return } func (s *LDAPStore) Ready() error { for _, ls := range s.sources { err := ls.Ready() if err != nil { return err } } return nil } func splitDC(base string) string { pos1 := strings.Index(base, "=") pos2 := strings.Index(base, ",") // TODO:more condition return base[pos1+1 : pos2] }
package storage import ( "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" log "code.google.com/p/log4go" "fairy/config" ) type ProductBrief struct { Product_id uint32 Product_name string Product_type uint32 price uint32 img string //brief string } type Product struct { Product_id uint32 Product_name string Product_type uint32 Price uint32 Img string Details string } func NewInstance(cfg *config.MysqlConfig) { // set default database link := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", cfg.Usr, cfg.Passwd, cfg.Server, cfg.Name) orm.RegisterDataBase("default", "mysql", link, 30, 30) } func GetProductList(merchant_id int) (int64, []ProductBrief, error) { var pts []ProductBrief o := orm.NewOrm() num, err := o.Raw("SELECT product_id, product_name, product_type, price, img FROM v1_product WHERE merchant_id = ?", merchant_id).QueryRows(&pts) if err != nil { log.Warn("GetProduct failed err = %s, merchant_id = %d", err, merchant_id) return 0, pts, err } return num, pts, nil } func GetProduct(product_id int) (Product, error) { var pt Product o := orm.NewOrm() err := o.Raw("SELECT product_id, product_name, product_type, price, img, details FROM v1_product WHERE product_id = ?", product_id).QueryRow(&pt) if err != nil { log.Warn("GetProduct failed err = %s, product_id = %d", err, product_id) return pt, err } return pt, nil } func SetProduct(p* Product) error { if p.product_id == 0 { return createProduct(p) } return editProduct(p) } func createProduct(p* Product) error { return nil } func editProduct(p* Product) error { return nil } func RemoveProduct(product_id int) error { // update status into config.STATUS_DELETE return nil } type Order struct { Order_id uint32 Detail []stirng } func GetOrderList(uid int, offset int, limit int) ([]Order, error) { return nil, nil } func CreateOrder(uid int, order Order) (error) { return nil } func GetOrderDetail(order_id int) (Order, error) { var order Order return order, nil } func RemoveOrder(order_id int) (Order, error) { var order Order return order, nil }
package main import ( "fmt" "io/ioutil" "os" "github.com/gocarina/gocsv" ) func WriteToFile(records []PaymentRecord) (*os.File, error) { f, err := ioutil.TempFile("./records", "record") if err != nil { return nil, fmt.Errorf("cannot create temp file: %v", err) } err = gocsv.MarshalFile(records, f) if err != nil { return nil, fmt.Errorf("cannot write csv to the temp file: %v", err) } return f, nil }
package main import ( "io/ioutil" "os" "path/filepath" "time" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/quick" "github.com/therecipe/qt/widgets" ) func displayWidgets() { //Label label := widgets.NewQLabel2("This Is A Label", nil, 0) label.SetWindowTitle("Label") addWidget(label) //Text Browser textBrowser := widgets.NewQTextBrowser(nil) textBrowser.SetWindowTitle("Text Browser") textBrowser.SetText("This Is A Text Browser") addWidget(textBrowser) //Graphics View graphicsView := widgets.NewQGraphicsView(nil) graphicsView.SetWindowTitle("Graphics View") scene := widgets.NewQGraphicsScene(nil) scene.AddText("This Is A Graphics View (+ Graphics Scene)", gui.NewQFont()) scene.AddRect2(0, 0, scene.Width(), scene.Height(), gui.NewQPen(), gui.NewQBrush()) graphicsView.SetScene(scene) addWidget(graphicsView) //Calendar Widget calendarWidget := widgets.NewQCalendarWidget(nil) calendarWidget.SetWindowTitle("Calendar Widget") addWidget(calendarWidget) //LCD Number lcdNumber := widgets.NewQLCDNumber(nil) lcdNumber.SetWindowTitle("LCD Number") lcdNumber.SetDigitCount(15) lcdNumber.Display("0123456789.-ABC") addWidget(lcdNumber) //Progress Bar progressBar := widgets.NewQProgressBar(nil) progressBar.SetWindowTitle("Progress Bar") progressBar.SetMinimum(0) progressBar.SetMaximum(1000) progressBar.SetValue(progressBar.Maximum() / 2) progressBar.ConnectValueChanged(func(value int) { if value == progressBar.Maximum() { progressBar.SetValue(progressBar.Minimum()) } }) go func() { for range time.NewTicker(500 * time.Millisecond).C { progressBar.SetValue(progressBar.Value() + 50) } }() addWidget(progressBar) //Quick Widget quickWidget := quick.NewQQuickWidget(nil) quickWidget.SetWindowTitle("Quick Widget") quickWidget.SetResizeMode(quick.QQuickWidget__SizeRootObjectToView) path := filepath.Join(os.TempDir(), "tmpQuickWidget.qml") ioutil.WriteFile(path, []byte("import QtQuick 2.0\nRectangle{width: 320; height: 320; color:\"red\"}"), 0644) quickWidget.SetSource(core.QUrl_FromLocalFile(path)) addWidget(quickWidget) }
package bca import ( "fmt" "net/url" ) type BalanceInformation struct { AccountDetailDataSuccess []AccountDetailDataSuccess `json:"AccountDetailDataSuccess"` AccountDetailDataFailed []AccountDetailDataFailed `json:"AccountDetailDataFailed"` } type AccountDetailDataSuccess struct { AccountNumber string `json:"AccountNumber"` Currency string `json:"Currency"` Balance string `json:"Balance"` AvailableBalance string `json:"AvailableBalance"` FloatAmount string `json:"FloatAmount"` HoldAmount string `json:"HoldAmount"` Plafon string `json:"Plafon"` } type AccountDetailDataFailed struct { English string `json:"English"` Indonesian string `json:"Indonesian"` AccountNumber string `json:"AccountNumber"` } type BalanceInformationRequest struct { AccountNumbers string `json:"AccountNumbers"` } func (r *BalanceInformationRequest) Get(accessToken string) (BalanceInformation, error) { var result BalanceInformation rq := createRequest("GET", fmt.Sprintf("/banking/v3/corporates/%s/accounts/%s", url.PathEscape(CorporateId), url.PathEscape(r.AccountNumbers))) rq.Sign(accessToken) err := rq.Request(&result) return result, err }
package sort // RadixSort 基数排序 func RadixSort(arr *[]int, maxNumber int) { buckets := make([][]int, 10) mod, dev := 10, 1 for i := 0; i < maxNumber; i, dev, mod = i+1, dev*10, mod*10 { for j := 0; j < len(*arr); j++ { bkPos := (*arr)[j] % mod / dev buckets[bkPos] = append(buckets[bkPos], (*arr)[j]) } var pos int for j := 0; j < len(buckets);j++ { for bj := range buckets[j] { v := buckets[j][bj] (*arr)[pos] = v pos++ } if len(buckets[j]) > 0 { buckets[j] = []int{} } } } }
package main import ( "fmt" "testing" ) func TestRepeatedString(t *testing.T) { testCases := []struct { s string n, want int64 }{ { s: "aba", n: 10, want: 7, }, { s: "a", n: 1000000000000, want: 1000000000000, }, { s: "epsxyyflvrrrxzvnoenvpegvuonodjoxfwdmcvwctmekpsnamchznsoxaklzjgrqruyzavshfbmuhdwwmpbkwcuomqhiyvuztwvq", n: 549382313570, want: 16481469408, }, } for _, tC := range testCases { t.Run(fmt.Sprintf("%v x %v", tC.s, tC.n), func(t *testing.T) { if result := repeatedString(tC.s, tC.n); result != tC.want { t.Fatalf("repeatedString(%v, %v) == '%v', wanted '%v'", tC.s, tC.n, result, tC.want) } }) } }
package ddl import ( "errors" "github.com/iftsoft/gopack/lla" "reflect" ) type ColumnMap map[string]string var ddlTableColumns map[string]ColumnMap func init() { ddlTableColumns = make(map[string]ColumnMap) } func RegisterObject(unit interface{}, table, alias string) { v := reflect.ValueOf(unit) if v.Kind() != reflect.Ptr || v.IsNil() { panic(strErrNullDataPtr) } obj := v.Elem() if obj.Kind() == reflect.Slice { panic(strErrDataIsSlice) } if _, ok := ddlTableColumns[table]; !ok { m := createColumnMap(unit, alias) ddlTableColumns[table] = m } } func GetTableColumnMap(table string) (m ColumnMap, ok bool) { m, ok = ddlTableColumns[table] return m, ok } func GetTableColumnName(table, field string) (string, bool) { if m, ok := ddlTableColumns[table]; ok { col, is := m[field] return col, is } return "", false } func createColumnMap(unit interface{}, alias string) ColumnMap { // Init and fill map of Value holders m := make(ColumnMap) iterateColumnMap(reflect.ValueOf(unit), m, alias, "", "") return m } // Recursive iterate through object structure and fill column map with value holders func iterateColumnMap(value reflect.Value, m ColumnMap, tab, pref, base string) { switch value.Kind() { case reflect.Ptr: if value.IsNil() { value.Set(reflect.New(value.Type().Elem())) } if !value.IsNil() { // Recursive call for pointer to struct iterateColumnMap(value.Elem(), m, tab, pref, base) } case reflect.Struct: t := value.Type() // Iterate through struct fields for i := 0; i < t.NumField(); i++ { field := t.Field(i) if field.PkgPath != "" && !field.Anonymous { // Skip unexported field continue } if field.Anonymous && field.Type.Kind() == reflect.Struct { // Recursive call for anonymous include struct iterateColumnMap(value.Field(i), m, tab, pref, base) continue } info := FieldInfo{} info.InitFieldInfo(field) if info.DdlType == Field_Skip { // Skip ignored field continue } key := info.FldName if base != "" { key = base + "." + info.FldName } if (info.DdlType & Field_Inc) == Field_Inc { // Recursive call for regular include struct iterateColumnMap(value.Field(i), m, tab, info.ColName, key) continue } if (info.DdlType & Field_Ref) == Field_Ref { // Recursive call for reference to other struct iterateColumnMap(value.Field(i), m, info.ColName, "", key) continue } // Add struct field to column map col := getFullColumnName(info.ColName, pref, tab) if _, ok := m[key]; !ok { m[key] = col } } } } type DBaseDAO struct { DBaseLink Name string timer lla.DurationTimer } func (dao *DBaseDAO) StartTimer() { dao.timer.StartTimer() } func (dao *DBaseDAO) StopTimer() int { return dao.timer.Microseconds() } func (dao *DBaseDAO) MakeSelectQuery(unit interface{}, bld *SelectBuilder) (err error) { if bld != nil { err = dao.ExecuteSelect(bld.BuildQuery(), bld.ParSlice(), unit) } else { err = errors.New(strErrNullBldPtr) } return err } func (dao *DBaseDAO) MakeSearchQuery(list interface{}, bld *SelectBuilder) (err error) { if bld != nil { err = dao.ExecuteSearch(bld.BuildQuery(), bld.ParSlice(), list) } else { err = errors.New(strErrNullBldPtr) } return err } func (dao *DBaseDAO) MakeEstimateQuery(result interface{}, bld *SelectBuilder) (err error) { if bld != nil { err = dao.ExecuteEstimate(bld.BuildQuery(), bld.ParSlice(), result) } else { err = errors.New(strErrNullBldPtr) } return err } func (dao *DBaseDAO) MakeUpdateQuery(bld *UpdateBuilder) (err error) { if bld != nil { err = dao.ExecuteUpdate(bld.BuildQuery(), bld.ParSlice()) } else { err = errors.New(strErrNullBldPtr) } return err } func (dao *DBaseDAO) MakeInsertQuery(bld *InsertBuilder) (err error) { if bld != nil { if bld.IsAutoInsert() { err = dao.ExecuteAutoInsert(bld.BuildQuery(), bld.ParSlice(), bld.AutoKeys(), bld.Dialect().IsReturnKey()) } else { err = dao.ExecuteInsert(bld.BuildQuery(), bld.ParSlice()) } } else { err = errors.New(strErrNullBldPtr) } return err } func (dao *DBaseDAO) MakeDeleteQuery(bld *DeleteBuilder) (err error) { if bld != nil { err = dao.ExecuteDelete(bld.BuildQuery(), bld.ParSlice()) } else { err = errors.New(strErrNullBldPtr) } return err }
package main import ( "context" "flag" "fmt" "net/http" "os" "strconv" "strings" "time" "github.com/adshao/go-binance/v2" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" log "github.com/sirupsen/logrus" ) const ( defaultUpdateInterval = "30s" defaultBaseURL = "https://api.binance.us" defaultHTTPServerPort = 8090 defaultPrometheusNamespace = "binance" defaultTrackAllSymbols = false defaultDebug = false defaultLogLevel = log.InfoLevel defaultPriceSymbol = "USD" ) type runtimeConfStruct struct { apiKey string secretKey string apiBaseURL string coinPrices *prometheus.GaugeVec balances *prometheus.GaugeVec symbolsOFInterest map[string]string trackAllSymbols bool manualSymbols string pricesSymbol string client *binance.Client registry *prometheus.Registry httpServerPort uint httpServ *http.Server updateInterval string updateIval time.Duration debug bool } var rConf runtimeConfStruct = runtimeConfStruct{ apiKey: "", secretKey: "", apiBaseURL: "", coinPrices: nil, balances: nil, symbolsOFInterest: make(map[string]string), manualSymbols: "", trackAllSymbols: false, client: nil, registry: prometheus.NewRegistry(), httpServerPort: 0, httpServ: nil, pricesSymbol: "", updateInterval: "", updateIval: 0, } func parsePriceCoins(symbolList string) { syms := strings.Split(symbolList, ",") for _, coinSym := range syms { // This maps market symbols to the specific coin we are interested in log.Debugf("> Tracking %s", strings.Join([]string{coinSym, rConf.pricesSymbol}, "")) rConf.symbolsOFInterest[coinSym+rConf.pricesSymbol] = coinSym } } func initParams() { // Flag values flag.StringVar(&rConf.apiKey, "apiKey", "", "Binance API Key.") flag.StringVar(&rConf.secretKey, "apiSecret", "", "Binance API secret Key.") flag.StringVar(&rConf.apiBaseURL, "apiBaseUrl", defaultBaseURL, "Binance base API URL.") flag.StringVar(&rConf.updateInterval, "updateInterval", defaultUpdateInterval, "Binance update interval") flag.UintVar(&rConf.httpServerPort, "httpServerPort", defaultHTTPServerPort, "HTTP server port.") flag.BoolVar(&rConf.debug, "debug", defaultDebug, "Set debug log level.") flag.BoolVar(&rConf.trackAllSymbols, "trackAll", defaultTrackAllSymbols, "Will set to track all market symbols.") flag.StringVar(&rConf.pricesSymbol, "priceSymbol", defaultPriceSymbol, "Set the default baseline currency symbol to calculate prices.") manualPrices := "" flag.StringVar(&manualPrices, "symbols", "", "Manually set the curency symbols to track (uses baseline to get market symbols).") flag.Parse() logLvl := defaultLogLevel if rConf.debug { logLvl = log.DebugLevel } log.SetLevel(logLvl) // Update interval parse updIval, err := time.ParseDuration(rConf.updateInterval) if err != nil { log.Errorf("Could not parse update interval duration, %v", err) os.Exit(-1) } rConf.updateIval = updIval parsePriceCoins(manualPrices) } func main() { // basic init and parsing of flags initParams() // Init binance client rConf.client = binance.NewClient(rConf.apiKey, rConf.secretKey) rConf.client.BaseURL = rConf.apiBaseURL // Register prom metrics path in http serv httpMux := http.NewServeMux() httpMux.Handle("/metrics", promhttp.InstrumentMetricHandler( rConf.registry, promhttp.HandlerFor(rConf.registry, promhttp.HandlerOpts{}), )) // Init & start serv rConf.httpServ = &http.Server{ Addr: fmt.Sprintf(":%d", rConf.httpServerPort), Handler: httpMux, } go func() { log.Infof("> Starting HTTP server at %s\n", rConf.httpServ.Addr) err := rConf.httpServ.ListenAndServe() if err != http.ErrServerClosed { log.Errorf("HTTP Server errored out %v", err) } }() // Init Prometheus Gauge Vectors rConf.balances = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: defaultPrometheusNamespace, Name: "balance", Help: fmt.Sprintf("Balance in account for assets"), }, []string{"symbol", "status"}, ) rConf.registry.MustRegister(rConf.balances) rConf.coinPrices = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: defaultPrometheusNamespace, Name: "price", Help: fmt.Sprintf("Symbol prices"), }, []string{"symbol"}, ) rConf.registry.MustRegister(rConf.coinPrices) // Regular loop operations below ticker := time.NewTicker(rConf.updateIval) for { log.Debug("> Updating....\n") // Update balances updateAccountBalances() // Update prices updatePrices() <-ticker.C } } func updateAccountBalances() error { acc, err := rConf.client.NewGetAccountService().Do(context.Background()) if err != nil { log.Errorf("Failed to get account Balances: %v\n", err) return err } for _, bal := range acc.Balances { free, _ := strconv.ParseFloat(bal.Free, 64) locked, _ := strconv.ParseFloat(bal.Locked, 64) if free+locked != 0 { log.Debugf("> Observing free in wallet %f for %s", free, bal.Asset) rConf.balances.WithLabelValues(bal.Asset, "free").Set(free) log.Debugf("> Observing locked in wallet %f for %s", locked, bal.Asset) rConf.balances.WithLabelValues(bal.Asset, "locked").Set(locked) if _, found := rConf.symbolsOFInterest[bal.Asset+rConf.pricesSymbol]; !found && (rConf.pricesSymbol != bal.Asset) { // This is a simple way to map trade market symbols (BTCUSD) to the asset we hold in wallet (BTC) log.Debugf("> Tracking %s", bal.Asset+rConf.pricesSymbol) rConf.symbolsOFInterest[bal.Asset+rConf.pricesSymbol] = bal.Asset } } } return nil } func updatePrices() error { prices, err := rConf.client.NewListPricesService().Do(context.Background()) if err != nil { log.Errorf("Failed to get prices: %v\n", err) return err } for _, p := range prices { if !rConf.trackAllSymbols { if symbol, ok := rConf.symbolsOFInterest[p.Symbol]; ok { // This observes values with asset label value (ie. BTC) and obviates baseline currency in label, // This is made like so to later have prometheus be able to easilly match wallet symbols and price symbols // (ie. Balance calculation vector `prices * wallet` will automatically match the right labels) price, _ := strconv.ParseFloat(p.Price, 64) log.Debugf("> Observing %f for %s", price, symbol) rConf.coinPrices.WithLabelValues(symbol).Set(price) } } else { // This observes values with full market symbol label value (BTCETH) price, _ := strconv.ParseFloat(p.Price, 64) log.Debugf("> Observing %f for %s", price, p.Symbol) rConf.coinPrices.WithLabelValues(p.Symbol).Set(price) } } return nil }
package models import ( "github.com/jinzhu/gorm" ) // OrderHistory Model type OrderHistory struct { gorm.Model OrderID int `json:"order_id" gorm:"not null" binding:"required"` Status int `json:"status" gorm:"not null; type:tinyint" binding:"required"` Desc string `json:"desc" gorm:"type:text"` Order Order }
package main import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "regexp" "strings" "sync" "github.com/fsnotify/fsnotify" ) type watcherConfig struct { ReposRoot string `json:"reposRoot"` WatchPath string `json:"watchPath"` WatchRegexp string `json:"watchRegexp"` Execute string `json:"execute"` } var config watcherConfig type logType string const ( logInfo logType = "info" logError logType = "error" ) var ( reposMutex *sync.Mutex reposWatcher *fsnotify.Watcher watcher *fsnotify.Watcher watcherRegexp *regexp.Regexp ) var currentlyWatching map[string]bool func main() { log(logInfo, "Starting repos watcher...") var err error reposWatcher, err = fsnotify.NewWatcher() checkError(err) defer reposWatcher.Close() watcher, err = fsnotify.NewWatcher() checkError(err) defer watcher.Close() reposMutex = &sync.Mutex{} currentlyWatching = map[string]bool{} configData, err := ioutil.ReadFile("config.json") checkError(err) err = json.Unmarshal(configData, &config) checkError(err) watcherRegexp, err = regexp.Compile(config.WatchRegexp) checkError(err) watchRepos(config.ReposRoot) } func checkError(e error) { if e != nil { log(logError, e.Error()) } } func watchRepos(reposRoot string) { info, err := os.Stat(reposRoot) if os.IsNotExist(err) { panic("repos root does not exists: " + reposRoot) } if !info.IsDir() { panic("specified repos root is not a directory: " + reposRoot) } reposDone := make(chan bool) go func() { for { select { case event := <-reposWatcher.Events: processReposEvent(event) } } }() err = reposWatcher.Add(reposRoot) if err != nil { log(logError, err.Error()) return } done := make(chan bool) go func() { for { select { case event := <-watcher.Events: processEvent(event) } } }() files, err := ioutil.ReadDir(reposRoot) for _, file := range files { addRepo(reposRoot + "/" + file.Name()) } <-done <-reposDone } func processReposEvent(event fsnotify.Event) { if event.Op&fsnotify.Create == fsnotify.Create { addRepo(event.Name) } else if event.Op&fsnotify.Chmod == fsnotify.Chmod { addRepo(event.Name) } else if event.Op&fsnotify.Rename == fsnotify.Rename { removeRepo(event.Name) } else if event.Op&fsnotify.Remove == fsnotify.Remove { removeRepo(event.Name) } } func processEvent(event fsnotify.Event) { separator := string(os.PathSeparator) if info, err := os.Stat(event.Name); os.IsNotExist(err) || info.IsDir() { return } dir, baseName := filepath.Split(event.Name) if !watcherRegexp.Match([]byte(baseName)) { return } reposRootParts := filterEmptyParts(strings.Split(config.ReposRoot, separator)) dirPathParts := filterEmptyParts(strings.Split(dir, separator)) repoPath := strings.Join(dirPathParts[:len(reposRootParts)+1], separator) execMessage := fmt.Sprintf("[RepoWatch] Executing \"%s\" in \"%s\"", config.Execute, repoPath) log(logInfo, execMessage) cmd := exec.Command("sh", "-c", config.Execute) cmd.Dir = repoPath output, err := cmd.Output() if err != nil { log(logError, err.Error()) return } log(logInfo, string(output)) } func filterEmptyParts(elements []string) []string { result := []string{} for _, element := range elements { if len(element) > 0 { result = append(result, element) } } return result } func addRepo(path string) { cleanPath := filepath.Clean(path) if info, err := os.Stat(cleanPath); err != nil || !info.IsDir() { return } targetPath := filepath.Clean(cleanPath + "/" + config.WatchPath) if info, err := os.Stat(targetPath); err != nil || !info.IsDir() { return } reposMutex.Lock() if _, ok := currentlyWatching[cleanPath]; !ok { log(logInfo, "[RepoWatch] Adding repo: "+cleanPath) watcher.Add(targetPath) currentlyWatching[cleanPath] = true } reposMutex.Unlock() } func removeRepo(path string) { cleanPath := filepath.Clean(path) targetPath := filepath.Clean(cleanPath + "/" + config.WatchPath) reposMutex.Lock() if _, ok := currentlyWatching[cleanPath]; ok { log(logInfo, "[RepoWatch] Removing repo: "+cleanPath) watcher.Remove(targetPath) delete(currentlyWatching, cleanPath) } reposMutex.Unlock() } func log(kind logType, message string) { fmt.Printf("%s: %s\n", kind, message) logFilename := fmt.Sprintf("%s.log", kind) f, _ := os.OpenFile(logFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f.Write([]byte(message + "\n")) f.Close() }
package po import ( "context" "encoding/json" "strconv" "time" "github.com/ChowRobin/fantim/model/vo" "github.com/ChowRobin/fantim/client" "github.com/jinzhu/gorm" ) type MessageRecord struct { Id int64 `gorm:"primary_key"` MsgId int64 `gorm:"column:msg_id"` Sender int64 `gorm:"column:sender"` ConversationId string `gorm:"column:conversation_id"` ConversationType int8 `gorm:"column:conversation_type"` MsgType int32 `gorm:"column:msg_type"` Content string `gorm:"column:content"` Ext string `gorm:"column:ext"` CreateTime *time.Time `gorm:"column:create_time"` UpdateTime *time.Time `gorm:"column:update_time"` } func (*MessageRecord) TableName() string { return "im_message" } func (m *MessageRecord) Create(ctx context.Context) error { conn, err := client.DBConn(ctx) if err != nil { return err } defer conn.Close() return conn.Create(m).Error } func (m *MessageRecord) Update(ctx context.Context) error { conn, err := client.DBConn(ctx) if err != nil { return err } defer conn.Close() return conn.Model(m).Update(m).Error } func MessagePoListToVo(msgList []*MessageRecord) []*vo.MessageBody { result := make([]*vo.MessageBody, 0, len(msgList)) for _, msg := range msgList { extMap := make(map[string]string) _ = json.Unmarshal([]byte(msg.Ext), &extMap) result = append(result, &vo.MessageBody{ ConversationType: int32(msg.ConversationType), ConversationId: msg.ConversationId, MsgType: msg.MsgType, Content: msg.Content, Ext: extMap, CreateTime: msg.CreateTime.Unix(), Sender: msg.Sender, MsgId: msg.MsgId, MsgIdStr: strconv.FormatInt(msg.MsgId, 10), }) } return result } func ListMessageByConversation(ctx context.Context, conversationId string, count int64) ([]*MessageRecord, error) { conn, err := client.DBConn(ctx) if err != nil { return nil, err } defer conn.Close() var list []*MessageRecord err = conn.Where("conversation_id=?", conversationId). Order("msg_id desc").Limit(count).Find(&list).Error if err == gorm.ErrRecordNotFound { return list, nil } return list, err } func ListByConversationAndMsgId(ctx context.Context, conversationId string, msgId, count int64) ([]*MessageRecord, error) { conn, err := client.DBConn(ctx) if err != nil { return nil, err } var list []*MessageRecord defer conn.Close() conn = conn.Debug() err = conn.Where("conversation_id=? and msg_id < ?", conversationId, msgId).Limit(count). Order("msg_id desc").Find(&list).Error if err == gorm.ErrRecordNotFound { return list, nil } return list, err } func ListByConversationAndCreateTime(ctx context.Context, conversationId string, count, createTime int64) ([]*MessageRecord, error) { conn, err := client.DBConn(ctx) if err != nil { return nil, err } var list []*MessageRecord defer conn.Close() conn = conn.Debug() err = conn.Where("conversation_id=? and create_time < ?", conversationId, createTime).Limit(count). Order("msg_id desc").Find(&list).Error if err == gorm.ErrRecordNotFound { return list, nil } return list, err } func MultiGetMessage(ctx context.Context, conversationId string, msgIds []int64) ([]*MessageRecord, error) { conn, err := client.DBConn(ctx) if err != nil { return nil, err } var list []*MessageRecord defer conn.Close() conn = conn.Debug() err = conn.Where("conversation_id=? and msg_id in (?)", conversationId, msgIds). Order("msg_id asc").Find(&list).Error if err == gorm.ErrRecordNotFound { return list, nil } return list, err }
package settings import ( "testing" ) func Test_Setup(t *testing.T) { Setup() if AppCfg.Name != "gohelper" { t.Error("settings parse conf/app.conf AppCfg.Name != gohelper") } if DatabaseCfg.Type != "mysql" { t.Error("settings parse conf/app.conf DatabaseCfg.Type != mysql") } if DatabaseCfg.Host != "127.0.0.1:3306" { t.Error("settings parse conf/app.conf DatabaseCfg.Host != 127.0.0.1:3306") } if DatabaseCfg.Name != "blog" { t.Error("settings parse conf/app.conf DatabaseCfg.Name != blog") } if DatabaseCfg.User != "root" { t.Error("settings parse conf/app.conf DatabaseCfg.User != root") } if DatabaseCfg.Passwd != "rootroot" { t.Error("settings parse conf/app.conf DatabaseCfg.Passwd != rootroot") } if RedisCfg.Host != "127.0.0.1:6379" { t.Error("settings parse conf/app.conf RedisCfg.Host != 127.0.0.1:6379") } if RedisCfg.Password != "" { t.Error("settings parse conf/app.conf RedisCfg.Password != ") } if RedisCfg.MaxIdle != 30 { t.Error("settings parse conf/app.conf RedisCfg.MaxIdle != 30") } if RedisCfg.MaxActive != 30 { t.Error("settings parse conf/app.conf RedisCfg.MaxActive != 30") } if RedisCfg.IdleTimeout != 200 { t.Error("settings parse conf/app.conf RedisCfg.IdleTimeout != 200") } t.Log(AppCfg.Version) }
// // Copyright 2020 IBM Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package resources import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "gopkg.in/yaml.v2" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" operatorv1 "github.com/IBM/ibm-auditlogging-operator/api/v1" testdata "github.com/IBM/ibm-auditlogging-operator/controllers/testutil" ) var _ = Describe("ConfigMaps", func() { const requestName = "example-commonaudit" const requestNamespace = "test" var ( commonAudit *operatorv1.CommonAudit //namespacedName = types.NamespacedName{Name: requestName, Namespace: requestNamespace} ) BeforeEach(func() { commonAudit = testdata.CommonAuditObj(requestName, requestNamespace) commonAudit.Spec.Outputs.Splunk.EnableSIEM = testdata.SplunkEnable commonAudit.Spec.Outputs.Syslog.EnableSIEM = testdata.QRadarEnable commonAudit.Spec.Outputs.Splunk.Host = testdata.SplunkHost commonAudit.Spec.Outputs.Splunk.Port = testdata.SplunkPort commonAudit.Spec.Outputs.Splunk.Token = testdata.SplunkToken commonAudit.Spec.Outputs.Splunk.TLS = testdata.SplunkTLS commonAudit.Spec.Outputs.Syslog.Host = testdata.QRadarHost commonAudit.Spec.Outputs.Syslog.Port = testdata.QRadarPort commonAudit.Spec.Outputs.Syslog.Hostname = testdata.QRadarHostname commonAudit.Spec.Outputs.Syslog.TLS = testdata.QRadarTLS }) Context("Build Fluentd Config", func() { It("Should include enabled output plugins", func() { result := buildFluentdConfig(commonAudit) Expect(result).Should(Equal(testdata.ExpectedFluentdConfig)) }) }) Context("Build Fluentd ConfigMap named "+FluentdDaemonSetName+"-"+SourceConfigName, func() { It("Should build source configmap", func() { result, err := BuildFluentdConfigMap(commonAudit, FluentdDaemonSetName+"-"+SourceConfigName) Expect(err).ToNot(HaveOccurred()) ds := DataS{} dataMap := make(map[string]string) err = yaml.Unmarshal([]byte(testdata.ExpectedSourceConfig), &ds) Expect(err).ToNot(HaveOccurred()) dataMap[SourceConfigKey] = ds.Value Expect(err).ToNot(HaveOccurred()) Expect(result.Data).Should(Equal(dataMap)) }) }) Context("Build Fluentd Splunk Config", func() { It("Should build Splunk configmap with instance host, port, and token", func() { result := buildFluentdSplunkConfig(commonAudit) Expect(result).Should(Equal(testdata.ExpectedSplunkConfig)) }) }) Context("Build Fluentd QRadar Config", func() { It("Should build Syslog configmap with instance host, port, and hostname", func() { result := buildFluentdQRadarConfig(commonAudit) Expect(result).Should(Equal(testdata.ExpectedQRadarConfig)) }) }) Context("Update SIEM Config", func() { It("Should update found configmap with instance configs", func() { dq := DataQRadar{} dataMap := make(map[string]string) data := testdata.BadQRadarConfig err := yaml.Unmarshal([]byte(data), &dq) Expect(err).NotTo(HaveOccurred()) dataMap[QRadarConfigKey] = dq.Value foundCM := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: FluentdDaemonSetName + "-" + QRadarConfigName, Namespace: requestNamespace, }, Data: dataMap, } result := UpdateSIEMConfig(commonAudit, foundCM) expectedResult := `<store> @type remote_syslog host test-qradar.fyre.ibm.com port 514 hostname test-syslog tls false protocol tcp ca_file /fluentd/etc/tls/qradar.crt packet_size 4096 program fluentd <buffer> @type file </buffer> <format> @type single_value message_key message </format> </store>` Expect(result).Should(Equal(expectedResult)) }) }) Context("Equal SIEM Config", func() { It("Should return whether or not instance configs are equal to configmap data", func() { dq := DataQRadar{} dataMap := make(map[string]string) // tls is missing data := testdata.BadQRadarConfigMissingTLS err := yaml.Unmarshal([]byte(data), &dq) Expect(err).NotTo(HaveOccurred()) dataMap[QRadarConfigKey] = dq.Value foundCM := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: FluentdDaemonSetName + "-" + QRadarConfigName, Namespace: requestNamespace, }, Data: dataMap, } result, missing := EqualSIEMConfig(commonAudit, foundCM) Expect(result).Should(BeFalse()) Expect(missing).Should(BeTrue()) }) }) })
// Double-linked list // User adds listItem object into his structure // and uses structPtr() to get the pointer to his object by the pointer to listItem object. package cache import "unsafe" type listItem struct { next *listItem prev *listItem } // initialize list func listInit(l *listItem) { l.next = l l.prev = l } // first list item func listFirst(l *listItem) *listItem { return l.next } // last list item func listLast(l *listItem) *listItem { return l.prev } // link 2 items to each other func listLink2(l, r *listItem) { l.next = r r.prev = l } // unlink func listUnlink(item *listItem) { listLink2(item.prev, item.next) } // append func listAppend(item, after *listItem) { listLink2(item, after.next) listLink2(after, item) } // Get pointer to structure object by pointer and offset to its field // e.g.: // userObject := (*userStruct)(structPtr(unsafe.Pointer(listPtr), unsafe.Offsetof(userStruct{}.listName))) func structPtr(fieldPtr unsafe.Pointer, fieldOff uintptr) unsafe.Pointer { return unsafe.Pointer(uintptr(fieldPtr) - fieldOff) }
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package common import ( "context" "github.com/rcrowley/go-metrics" log "github.com/sirupsen/logrus" "github.com/streamsets/datacollector-edge/api" "github.com/streamsets/datacollector-edge/api/validation" "github.com/streamsets/datacollector-edge/container/el" "github.com/streamsets/datacollector-edge/container/util" "strconv" "strings" "time" ) const StageConfig = "STAGE_CONFIG" type StageContextImpl struct { StageConfig *StageConfiguration Parameters map[string]interface{} Metrics metrics.Registry ErrorSink *ErrorSink ErrorStage bool ErrorRecordPolicy string } func (s *StageContextImpl) GetResolvedValue(configValue interface{}) (interface{}, error) { var err error switch t := configValue.(type) { case string: return s.resolveIfImplicitEL(configValue.(string)) case []interface{}: for i, val := range t { t[i], err = s.GetResolvedValue(val) if err != nil { return nil, err } } return configValue, nil case map[string]interface{}: for k, v := range t { t[k], err = s.GetResolvedValue(v) if err != nil { return nil, err } } return configValue, nil default: return configValue, nil } } func (s *StageContextImpl) resolveIfImplicitEL(configValue string) (interface{}, error) { if el.IsElString(configValue) { return el.Evaluate(configValue, "configName", s.Parameters) } else { return configValue, nil } } func (s *StageContextImpl) GetParameterValue(paramName string) interface{} { paramName = strings.Replace(paramName, el.PARAMETER_PREFIX, "", 1) paramName = strings.Replace(paramName, el.PARAMETER_SUFFIX, "", 1) if p, err := strconv.ParseInt(s.Parameters[paramName].(string), 10, 64); err == nil { return p } return s.Parameters[paramName] } func (s *StageContextImpl) GetMetrics() metrics.Registry { return s.Metrics } func (s *StageContextImpl) CreateRecord(recordSourceId string, value interface{}) (api.Record, error) { record, err := createRecord(recordSourceId, value) if err != nil { return nil, err } headerImplForRecord := record.GetHeader().(*HeaderImpl) headerImplForRecord.SetStageCreator(s.StageConfig.InstanceName) if s.ErrorRecordPolicy == ErrorRecordPolicyOriginal { // Clone the current record to the header for error record handling headerImplForRecord.SetSourceRecord(record.Clone()) } return record, err } func (s *StageContextImpl) ToError(err error, record api.Record) { errorRecord := constructErrorRecord(s.StageConfig.InstanceName, err, s.ErrorRecordPolicy, record) s.ErrorSink.ToError(s.StageConfig.InstanceName, errorRecord) } func (s *StageContextImpl) ReportError(err error) { s.ErrorSink.ReportError(s.StageConfig.InstanceName, err) } func (s *StageContextImpl) GetOutputLanes() []string { return s.StageConfig.OutputLanes } func (s *StageContextImpl) Evaluate( value string, configName string, ctx context.Context, ) (interface{}, error) { if el.IsElString(value) { evaluator, _ := el.NewEvaluator( configName, s.Parameters, []el.Definitions{ &el.StringEL{}, &el.MathEL{}, &el.RecordEL{Context: ctx}, &el.MapListEL{}, }, ) return evaluator.Evaluate(value) } else { return value, nil } } func (s *StageContextImpl) IsErrorStage() bool { return s.ErrorStage } // optional argument, first optional argument is configGroup, second optional argument- configName func (s *StageContextImpl) CreateConfigIssue(error string, optional ...interface{}) validation.Issue { issue := validation.Issue{ InstanceName: s.StageConfig.InstanceName, Level: StageConfig, Count: 1, Message: error, } if len(optional) > 0 { issue.ConfigGroup = optional[0].(string) } if len(optional) > 1 { issue.ConfigName = optional[1].(string) } return issue } func constructErrorRecord(instanceName string, err error, errorRecordPolicy string, record api.Record) api.Record { var recordToBeSentToError api.Record switch errorRecordPolicy { case ErrorRecordPolicyStage: recordToBeSentToError = record case ErrorRecordPolicyOriginal: headerForRecord := record.GetHeader().(*HeaderImpl) recordToBeSentToError = headerForRecord.GetSourceRecord() default: log.Errorf("Unsupported Error Record Policy: %s, Using the original record from source", errorRecordPolicy) headerForRecord := record.GetHeader().(*HeaderImpl) recordToBeSentToError = headerForRecord.GetSourceRecord() } headerImplForRecord := recordToBeSentToError.GetHeader().(*HeaderImpl) headerImplForRecord.SetErrorStageInstance(instanceName) headerImplForRecord.SetErrorMessage(err.Error()) headerImplForRecord.SetErrorTimeStamp(util.ConvertTimeToLong(time.Now())) return recordToBeSentToError }
package server import ( "encoding/json" "github.com/dublour/genesis_se_task3/pkg/binance" "github.com/dublour/genesis_se_task3/pkg/model" "log" "net/http" "os" ) func Respond(w http.ResponseWriter, r *http.Request, httpStatus int, data map[string]interface{}) { w.Header().Add("Content-Type", "application/json") w.WriteHeader(httpStatus) json.NewEncoder(w).Encode(data) //Log requests and response data log.Println("REQ:", r.URL.String(), "\nSTATUS:", httpStatus, "BODY:", data) } func main() { //Init log file logger, err := os.OpenFile(LogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { log.Fatal(err) } defer logger.Close() log.SetOutput(logger) //Common case for incorrect endpoints http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mess := map[string]interface{}{ "status": "Fail", } Respond(w, r, http.StatusNotFound, mess) }) //Registration of new account //Require `email` and `password` fields in URL //Append new user in `UsersFile` and return `{"status":"Ok"}` if successful http.HandleFunc("/user/create", func(w http.ResponseWriter, r *http.Request) { email := r.URL.Query().Get("email") password := r.URL.Query().Get("password") httpStatus, err := UserRegister(email, password) status := "Ok" if err != nil { status = err.Error() //Detail about what went wrong } mess := map[string]interface{}{ "status": status, } Respond(w, r, httpStatus, mess) }) //Get an API-token for registered users //Require `email` and `password` fields in URL //Return `{"status":"Ok","token":"############"}` if successful http.HandleFunc("/user/login", func(w http.ResponseWriter, r *http.Request) { email := r.URL.Query().Get("email") password := r.URL.Query().Get("password") token, httpStatus, err := UserLogin(email, password) mess := map[string]interface{}{} if err == nil { mess = map[string]interface{}{ "status": "Ok", "token": token, } } else { mess = map[string]interface{}{ "status": err.Error(), } } Respond(w, r, httpStatus, mess) }) //Get a current cost of BitCoin in UAH //Require `token` in URL on `X-API-Key` in Header (more priority) //Return `{"status":"Ok","BTCUAH":$$$$$$}` if successful http.HandleFunc("/btcRate", func(w http.ResponseWriter, r *http.Request) { var urlToken, headerToken, token string urlToken = r.URL.Query().Get("token") headerToken = r.Header.Get("X-API-Key") if headerToken != "" { token = headerToken } else { token = urlToken } if IsAvailableToken(token) { //Find user in database with that token cost, err := Cost("BTCUAH") if err == nil { mess := map[string]interface{}{ "status": "Ok", "BTCUAH": cost, } Respond(w, r, http.StatusOK, mess) } else { mess := map[string]interface{}{ "status": err.Error(), } Respond(w, r, http.StatusInternalServerError, mess) } return } if token == "" { mess := map[string]interface{}{ "status": "Missing token", } Respond(w, r, http.StatusBadRequest, mess) return } mess := map[string]interface{}{ "status": "Invalid token", } Respond(w, r, http.StatusForbidden, mess) }) http.ListenAndServe(ServerPort, nil) }