func (cmdr *Commander) Usage() { fmt.Printf("usage: %s cmd [cmd-flags] [cmd-args]\n", os.Args[0]) var groupNames sort.StringSlice cmdNamesByGroup := map[string]sort.StringSlice{} for _, cmd := range cmdr.Commands { if _, ok := cmdNamesByGroup[cmd.Group]; !ok { groupNames = append(groupNames, cmd.Group) } cmdNamesByGroup[cmd.Group] = append(cmdNamesByGroup[cmd.Group], cmd.Name) } groupNames.Sort() for _, gn := range groupNames { fmt.Printf("\n%s:\n", gn) cmdNamesByGroup[gn].Sort() for _, cn := range cmdNamesByGroup[gn] { cmd := cmdr.Commands[cn] fmt.Printf(" %-18s %s\n", cmd.Name, cmd.Description) } } fmt.Println() }
func ConfigList(configStore *config.Store, app, env string) error { cfg, err := configStore.GetApp(app, env) if err != nil { return err } if cfg == nil { return fmt.Errorf("unable to list config for %s.", app) } keys := sort.StringSlice{"ENV"} for k, _ := range cfg.Env() { keys = append(keys, k) } keys.Sort() for _, k := range keys { if k == "ENV" { log.Printf("%s=%s\n", k, env) continue } fmt.Printf("%s=%s\n", k, cfg.Env()[k]) } return nil }
func setUsage(commands map[string]Command) { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage:\n %s [http://cbfs:8484/] cmd [-opts] cmdargs\n", os.Args[0]) fmt.Fprintf(os.Stderr, "\nCommands:\n") ss := sort.StringSlice{} for k := range commands { ss = append(ss, k) } ss.Sort() for _, k := range ss { fmt.Fprintf(os.Stderr, " %s %s\n", k, commands[k].Argstr) } fmt.Fprintf(os.Stderr, "\n---- Subcommand Options ----\n") for _, k := range ss { if commands[k].Flags != nil { fmt.Fprintf(os.Stderr, "\n%s:\n", k) commands[k].Flags.PrintDefaults() } } os.Exit(1) } }
func setUpdate(prev []string, v interface{}) []string { m := map[string]bool{} for _, v := range prev { m[v] = true } switch i := v.(type) { case nil: case string: m[i] = true case []interface{}: for _, v := range i { val, ok := v.(string) if ok { m[val] = true } } } rv := sort.StringSlice{} for k := range m { rv = append(rv, k) } rv.Sort() return []string(rv) }
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage:\n%s [opts] template\n\nOptions:\n", os.Args[0]) flag.PrintDefaults() tdoc := map[string]string{ "{{.ID}}": "numeric ID of repo", "{{.Owner.Login}}": "github username of repo owner", "{{.Owner.ID}}": "github numeric id of repo owner", "{{.Name}}": "short name of repo (e.g. gitmirror)", "{{.FullName}}": "full name of repo (e.g. dustin/gitmirror)", "{{.Language}}": "repository language (if detected)", } a := sort.StringSlice{} for k := range tdoc { a = append(a, k) } a.Sort() fmt.Fprintf(os.Stderr, "\nTemplate parameters:\n") tw := tabwriter.NewWriter(os.Stderr, 8, 4, 2, ' ', 0) for _, k := range a { fmt.Fprintf(tw, " %v\t- %v\n", k, tdoc[k]) } tw.Flush() fmt.Fprintf(os.Stderr, "\nExample templates:\n"+ " http://example.com/gitmirror/{{.FullName}}.git\n"+ " http://example.com/gitmirror/{{.Owner.Login}}/{{.Language}}/{{.Name}}.git\n"+ " http://example.com/gitmirror/{{.Name}}.git\n") } }
// computeChecksum computes checksum of all servers in the ring func (r *hashRing) ComputeChecksum() { var addresses sort.StringSlice var buffer bytes.Buffer r.servers.Lock() for address := range r.servers.byAddress { addresses = append(addresses, address) } addresses.Sort() for _, address := range addresses { buffer.WriteString(address) buffer.WriteString(";") } old := r.servers.checksum r.servers.checksum = farm.Fingerprint32(buffer.Bytes()) r.ringpop.ringEvent(RingChecksumEvent{ OldChecksum: old, NewChecksum: r.servers.checksum, }) r.servers.Unlock() }
// 校验消息是否是从微信服务器发送过来的. // 使用 buf 能提高一点性能 和 减少一些对 GC 的压力, buf 的长度最好 >=128 func _CheckSignature(signature, timestamp, nonce, token string, buf []byte) bool { const hashsumLen = 40 // sha1 if len(signature) != hashsumLen { return false } bufLen := hashsumLen + len(timestamp) + len(nonce) + len(token) if len(buf) < bufLen { buf = make([]byte, hashsumLen, bufLen) } else { buf = buf[:hashsumLen] } strArray := sort.StringSlice{token, timestamp, nonce} strArray.Sort() buf = append(buf, strArray[0]...) buf = append(buf, strArray[1]...) buf = append(buf, strArray[2]...) hashsumArray := sha1.Sum(buf[hashsumLen:]) // require go1.2+ hashsumHexBytes := buf[:hashsumLen] hex.Encode(hashsumHexBytes, hashsumArray[:]) // 采用 subtle.ConstantTimeCompare 是防止 计时攻击! if rslt := subtle.ConstantTimeCompare(hashsumHexBytes, []byte(signature)); rslt == 1 { return true } return false }
func display(w io.Writer, format string, title string, supportedSites map[string]string) { var urls sort.StringSlice for url := range supportedSites { urls = append(urls, url) } urls.Sort() switch format { case "html": fmt.Fprint(w, "\t\tSupported "+title+":") fmt.Fprint(w, "<br />\n") for _, url := range urls { var s string if strings.Contains(url, "http") { s = "\t\t<a href=\"" + url + "\">" + supportedSites[url] + "</a><br />\n" } else { s = "\t\t<a href=\"http://www." + url + "\">" + supportedSites[url] + "</a><br />\n" } fmt.Fprint(w, s) } default: fmt.Fprint(w, "Supported journals:\n\n") for _, url := range urls { fmt.Fprint(w, supportedSites[url]+"\t\t"+url+"\n") } } }
// findFile finds a file that ends with name.md, ignoring leading digits and dashes (to support blogging and // sorting of .md files a-là jekyll) and returns it's name. It returns an error if no path is found. // Names ending with / are automatically added index to them. If there are multiple paths ending with name.md, // they are sorted lexicographically and the biggest path is returned, so e.g. 2014-01-01-results.md // will have preference over 2013-01-01-results.md func findFile(root, name string) (string, error) { if strings.HasSuffix(name, "/") || name == "" { name += "index" } name += ".md" basename := filepath.Base(name) dirname := filepath.Dir(name) matches, err := filepath.Glob(filepath.Join(root, dirname, "*"+basename)) if err != nil { return "", err } if len(matches) == 0 { return "", fmt.Errorf("no matches for pattern %s", name) } var prefixes sort.StringSlice for _, m := range matches { m = filepath.Base(m) if p := m[:len(m)-len(basename)]; isDigital(p) { prefixes = append(prefixes, p) } } if len(prefixes) == 0 { return "", fmt.Errorf("no matches for pattern %s", name) } prefixes.Sort() return filepath.Join(root, dirname, prefixes[len(prefixes)-1]+basename), nil }
// UploadDirTree uploads a local directory and all of its subfolders // localDir -> path to the local folder to upload along with all of its subfolders. // remoteRootDir -> the root folder on the FTP server where to store the localDir tree. // excludedDirs -> a slice of folder names to exclude from the uploaded directory tree. // callback -> a callback function, which is called synchronously. Do remember to collect data in a go routine for instance if you do not want the upload to block. // Returns the number of files uploaded and an error if any. // // The current workding directory is set back to the initial value at the end. func (ftp *FTP) UploadDirTree(localDir string, remoteRootDir string, maxSimultaneousConns int, excludedDirs []string, callback Callback) (n int, err error) { if len(remoteRootDir) == 0 { return n, errors.New("A valid remote root folder with write permission needs specifying.") } var pwd string if pwd, err = ftp.Pwd(); err != nil { return } if _, err = ftp.Cwd(remoteRootDir); err != nil { return n, nil } //go back to original wd defer ftp.Cwd(pwd) //all lower case var exDirs sort.StringSlice if len(excludedDirs) > 0 { exDirs = sort.StringSlice(excludedDirs) for _, v := range exDirs { v = strings.ToLower(v) } exDirs.Sort() } err = ftp.uploadDirTree(localDir, exDirs, callback, &n) if err != nil { ftp.writeInfo(fmt.Sprintf("An error while uploading the folder %s occurred.", localDir)) } return n, err }
func (ee EtcdEnvironment) String() (out string) { norm := normalizeSvcEnv(ee) if val, ok := norm["DISCOVERY_URL"]; ok { delete(norm, "DISCOVERY_URL") if _, ok := norm["DISCOVERY"]; !ok { norm["DISCOVERY"] = val } } var sorted sort.StringSlice for k, _ := range norm { sorted = append(sorted, k) } sorted.Sort() out += "[Service]\n" for _, key := range sorted { val := norm[key] out += fmt.Sprintf("Environment=\"ETCD_%s=%s\"\n", key, val) } return }
// Returns the code for an ambigious amino acid. func AminoAcidCode(aa string) string { aa = strings.ToUpper(aa) if len(aa) == 1 { return aa } letters := sort.StringSlice{aa[:]} letters.Sort() sorted := strings.Join([]string(letters), "") switch sorted { case "AG": return "R" case "CT": return "Y" case "AC": return "M" case "GT": return "K" case "CG": return "S" case "AT": return "W" case "ACT": return "H" case "CGT": return "B" case "ACG": return "V" case "AGT": return "D" case "ACGT": return "N" } return aa }
// sortFlags returns the flags as a slice in lexicographical sorted order. func sortFlags(flags map[string]*Flag) []*Flag { var list sort.StringSlice for _, f := range flags { if len(f.Names) == 1 { list = append(list, f.Names[0]) continue } found := false fName := strings.TrimPrefix(strings.TrimPrefix(f.Names[0], "#"), "-") for _, name := range list { if name == fName { found = true break } } if !found { list = append(list, fName) } } list.Sort() result := make([]*Flag, len(list)) for i, name := range list { result[i] = flags[name] } return result }
func generalHelp() { out := tabwriter.NewWriter(os.Stderr, 0, 8, 1, '\t', 0) exe := filepath.Base(os.Args[0]) fmt.Fprintf(out, "USAGE:\n\t%s [global options] <command> [command options] [arguments...]\n\n", exe) fmt.Fprintf(out, "VERSION:\n\t%s\n\n", Version) fmt.Fprintf(out, "COMMANDS:\n") names := sort.StringSlice{} for name, _ := range subcommands { names = append(names, name) } names.Sort() for _, name := range names { cmd := subcommands[name] fmt.Fprintf(out, "\t%s\t%s\n", name, cmd.desc()) } fmt.Fprintln(out) fmt.Fprintf(out, "GLOBAL OPTIONS:\n") flag.VisitAll(func(f *flag.Flag) { prefix := "-" if len(f.Name) > 1 { prefix = "--" } fmt.Fprintf(out, "\t%s%s=%s\t%s\n", prefix, f.Name, f.DefValue, f.Usage) }) fmt.Fprintln(out) fmt.Fprintf(out, "Run \"%s help <command>\" for more details about a command.\n", exe) }
func (l list) String() string { var lines sort.StringSlice for k, v := range l.entry { lines = append(lines, fmt.Sprintf("%q:%v,\n", k, v)) } lines.Sort() return strings.Join(lines, "") }
func sliceData(lineData []byte) sort.StringSlice { var names sort.StringSlice for _, n := range strings.Split(string(lineData), ",") { names = append(names, n) } names.Sort() return names }
// TestListUnitFilesOrder simply checks if "fleetctl list-unit-files" returns // an ordered list of units func TestListUnitFilesOrder(t *testing.T) { cluster, err := platform.NewNspawnCluster("smoke") if err != nil { t.Fatal(err) } defer cluster.Destroy(t) m, err := cluster.CreateMember() if err != nil { t.Fatal(err) } _, err = cluster.WaitForNMachines(m, 1) if err != nil { t.Fatal(err) } // Combine units var units []string for i := 1; i <= 20; i++ { unit := fmt.Sprintf("fixtures/units/hello@%02d.service", i) stdout, stderr, err := cluster.Fleetctl(m, "submit", unit) if err != nil { t.Fatalf("Failed to submit a batch of units: \nstdout: %s\nstder: %s\nerr: %v", stdout, stderr, err) } units = append(units, unit) } // make sure that all unit files will show up _, err = cluster.WaitForNUnitFiles(m, 20) if err != nil { t.Fatal("Failed to run list-unit-files: %v", err) } stdout, _, err := cluster.Fleetctl(m, "list-unit-files", "--no-legend", "--fields", "unit") if err != nil { t.Fatal("Failed to run list-unit-files: %v", err) } outUnits := strings.Split(strings.TrimSpace(stdout), "\n") var sortable sort.StringSlice for _, name := range units { n := path.Base(name) sortable = append(sortable, n) } sortable.Sort() var inUnits []string for _, name := range sortable { inUnits = append(inUnits, name) } if !reflect.DeepEqual(inUnits, outUnits) { t.Fatalf("Failed to get a sorted list of units from list-unit-files") } }
// Units lists all Units stored in the Registry, ordered by name. This includes both global and non-global units. func (r *EtcdRegistry) Units() ([]job.Unit, error) { key := r.prefixed(jobPrefix) opts := &etcd.GetOptions{ Sort: true, Recursive: true, } res, err := r.kAPI.Get(r.ctx(), key, opts) if err != nil { if isEtcdError(err, etcd.ErrorCodeKeyNotFound) { err = nil } return nil, err } // Fetch all units by hash recursively to avoid sending N requests to Etcd. hashToUnit, err := r.getAllUnitsHashMap() if err != nil { log.Errorf("failed fetching all Units from etcd: %v", err) return nil, err } unitHashLookupFunc := func(hash unit.Hash) *unit.UnitFile { stringHash := hash.String() unit, ok := hashToUnit[stringHash] if !ok { log.Errorf("did not find Unit %v in list of all units", stringHash) return nil } return unit } uMap := make(map[string]*job.Unit) for _, dir := range res.Node.Nodes { u, err := r.dirToUnit(dir, unitHashLookupFunc) if err != nil { log.Errorf("Failed to parse Unit from etcd: %v", err) continue } if u == nil { continue } uMap[u.Name] = u } var sortable sort.StringSlice for name, _ := range uMap { sortable = append(sortable, name) } sortable.Sort() units := make([]job.Unit, 0, len(sortable)) for _, name := range sortable { units = append(units, *uMap[name]) } return units, nil }
//Pulls all keys out of a map, sorts them, and returns them as an array. //This alows stable/sorted iteration over maps func sortedKeys(inMap map[string]Param) []string { keys := sort.StringSlice{} for key, _ := range inMap { keys = append(keys, key) } keys.Sort() return keys }
func (gen *modelGenerator) emitHeader(banner string) { imports := make(map[string]string, 0) visited := make(map[rdl.TypeName]rdl.TypeName, 0) for _, t := range gen.schema.Types { gen.requiredImports(t, imports, visited) } gen.emit(generationHeader(banner)) gen.emit("\n\npackage " + generationPackage(gen.schema, gen.ns) + "\n") if len(imports) > 0 { rdlEmitted := false jsonEmitted := false fmtEmitted := false var imp sort.StringSlice for k := range imports { if k == string(gen.schema.Name) { continue } kk := fmt.Sprintf("%q", k) if k == "fmt" { fmtEmitted = true } else if k == "encoding/json" { jsonEmitted = true } n := imports[k] if n != "" { if n == "rdl" { rdlEmitted = true } kk = n + " " + kk } imp = append(imp, kk) } imp.Sort() gen.emit("\nimport (\n") for _, k := range imp { gen.emit("\t" + k + "\n") } gen.emit(")\n") if rdlEmitted { gen.emit("\nvar _ = rdl.Version\n") } if jsonEmitted { if !rdlEmitted { gen.emit("\n") } gen.emit("var _ = json.Marshal\n") } if fmtEmitted { if !jsonEmitted && !rdlEmitted { gen.emit("\n") } gen.emit("var _ = fmt.Printf\n") } } }
func (c *consistencyChecker) vmiCompare(pod *api.Pod, interfaceId string) bool { vmi, err := types.VirtualMachineInterfaceByUuid(c.client, interfaceId) if err != nil { return false } var serviceIpNames sort.StringSlice refs, err := vmi.GetFloatingIpBackRefs() if err == nil { serviceIpMap := make(map[string]bool) for _, ref := range refs { name := strings.Join(ref.To, ":") if _, ok := serviceIpMap[name]; !ok { serviceIpMap[name] = true serviceIpNames = append(serviceIpNames, name) } } } serviceIpNames.Sort() var serviceCacheNames sort.StringSlice services, err := c.serviceStore.GetPodServices(pod) if err == nil { for _, service := range services { serviceName := ServiceName(c.config, service.Labels) serviceNet := fmt.Sprintf(ServiceNetworkFmt, serviceName) fqn := []string{c.config.DefaultDomain, service.Namespace, serviceNet, serviceNet, service.Name} if service.Spec.ClusterIP != "" { serviceCacheNames = append(serviceCacheNames, strings.Join(fqn, ":")) } if service.Spec.Type == api.ServiceTypeLoadBalancer || len(service.Spec.ExternalIPs) > 0 { publicFQN := strings.Split(c.config.PublicNetwork, ":") id := fmt.Sprintf("%s:%s:%s_%s", c.config.PublicNetwork, publicFQN[len(publicFQN)-1], service.Namespace, service.Name) serviceCacheNames = append(serviceCacheNames, id) } } } serviceCacheNames.Sort() result := CompareSortedLists( serviceCacheNames, serviceIpNames, func(key string) { glog.Errorf("interface %s: missing floating-ip for %s", vmi.GetName(), key) }, func(key string) { glog.Errorf("interface %s: invalid floating-ip %s", vmi.GetName(), key) }, func(key string) bool { return true }, ) return result }
func (m Manifest) EntryNames() []string { var names sort.StringSlice = make([]string, 0) for k, _ := range m { names = append(names, k) } names.Sort() return names }
// Schedule returns all ScheduledUnits known by fleet, ordered by name func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) { req := etcd.Get{ Key: path.Join(r.keyPrefix, jobPrefix), Sorted: true, Recursive: true, } res, err := r.etcd.Do(&req) if err != nil { if isKeyNotFound(err) { err = nil } return nil, err } heartbeats := make(map[string]string) uMap := make(map[string]*job.ScheduledUnit) for _, dir := range res.Node.Nodes { _, name := path.Split(dir.Key) u := &job.ScheduledUnit{ Name: name, TargetMachineID: dirToTargetMachineID(&dir), } heartbeats[name] = dirToHeartbeat(&dir) uMap[name] = u } states, err := r.statesByMUSKey() if err != nil { return nil, err } var sortable sort.StringSlice // Determine the JobState of each ScheduledUnit for name, su := range uMap { sortable = append(sortable, name) key := MUSKey{ machID: su.TargetMachineID, name: name, } us := states[key] js := determineJobState(heartbeats[name], su.TargetMachineID, us) su.State = &js } sortable.Sort() units := make([]job.ScheduledUnit, 0, len(sortable)) for _, name := range sortable { units = append(units, *uMap[name]) } return units, nil }
func (c *Client) CanonicalizedOSSHeaders() string { var t sort.StringSlice for k, v := range c.Request.Header { k = strings.ToLower(k) if strings.HasPrefix(k, "x-oss-") { t = append(t, k+":"+strings.Join(v, ",")+"\n") } } t.Sort() return strings.Join(t, "") }
// Schedule returns all ScheduledUnits known by fleet, ordered by name func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) { key := r.prefixed(jobPrefix) opts := &etcd.GetOptions{ Sort: true, Recursive: true, Quorum: true, } res, err := r.kAPI.Get(r.ctx(), key, opts) if err != nil { if isEtcdError(err, etcd.ErrorCodeKeyNotFound) { err = nil } return nil, err } heartbeats := make(map[string]string) uMap := make(map[string]*job.ScheduledUnit) for _, dir := range res.Node.Nodes { _, name := path.Split(dir.Key) u := &job.ScheduledUnit{ Name: name, TargetMachineID: dirToTargetMachineID(dir), } heartbeats[name] = dirToHeartbeat(dir) uMap[name] = u } states, err := r.statesByMUSKey() if err != nil { return nil, err } var sortable sort.StringSlice // Determine the JobState of each ScheduledUnit for name, su := range uMap { sortable = append(sortable, name) key := MUSKey{ machID: su.TargetMachineID, name: name, } us := states[key] js := determineJobState(heartbeats[name], su.TargetMachineID, us) su.State = &js } sortable.Sort() units := make([]job.ScheduledUnit, 0, len(sortable)) for _, name := range sortable { units = append(units, *uMap[name]) } return units, nil }
// Sign 微信公众号 url 签名. func Sign(token, timestamp, nonce string) (signature string) { strs := sort.StringSlice{token, timestamp, nonce} strs.Sort() buf := make([]byte, 0, len(token)+len(timestamp)+len(nonce)) buf = append(buf, strs[0]...) buf = append(buf, strs[1]...) buf = append(buf, strs[2]...) hashsum := sha1.Sum(buf) return hex.EncodeToString(hashsum[:]) }
// formatData returns an io.Reader loaded with dnsmasq formatted data func formatData(fmttr string, l list) io.Reader { var lines sort.StringSlice l.RLock() for k := range l.entry { lines = append(lines, fmt.Sprintf(fmttr+"\n", k)) } lines.Sort() l.RUnlock() return strings.NewReader(strings.Join(lines, "")) }
func createWorkbook(m map[string]messages) { var channelNames sort.StringSlice workbook := xlsx.NewFile() fullPath := filepath.Clean(filepath.Join(outputDir, filename)) // First, sort the map by channel name for channel := range m { channelNames = append(channelNames, channel) } channelNames.Sort() for _, channel := range channelNames { sheet, err := workbook.AddSheet(channel) if err != nil { panic(err) } sort.Sort(sort.Reverse(m[channel])) headingRow := sheet.AddRow() headingRow.AddCell().SetString("Timestamp") headingRow.AddCell().SetString("User") headingRow.AddCell().SetString("Message") if err := sheet.SetColWidth(0, 1, 20); err != nil { panic(err) } if err := sheet.SetColWidth(2, 2, 200); err != nil { panic(err) } for _, message := range m[channel] { messageRow := sheet.AddRow() messageRow.AddCell().SetString(message.Timestamp.Format("Jan 02, 2006 | 15:04")) messageRow.AddCell().SetString(message.User) messageRow.AddCell().SetString(message.Text) } } if err := os.MkdirAll(filepath.Dir(fullPath), os.ModePerm); err != nil { panic(err) } if err := workbook.Save(fullPath); err != nil { panic(err) } }
func ShowCssPaths() { var paths sort.StringSlice css, paths, err := Css() if err != nil { panic(err) } paths.Sort() fmt.Printf("Css Path: %s\n", css) fmt.Printf("Path Count: %d\n", len(paths)) for _, p := range paths { fmt.Println(p) } }
func (driver *Driver) getLunMapsSig() (string, error) { lunMap, err := driver.Client.GetLunMaps() if err != nil { return "", err } var lunMapsNameHref sort.StringSlice for _, lunMap := range lunMap { lunMapsNameHref = append(lunMapsNameHref, fmt.Sprintf("%s-%s", lunMap.Name, lunMap.Href)) } lunMapsNameHref.Sort() return strings.Join(lunMapsNameHref, ";"), err }