func (p *fileSystem) lsZip(data []byte) map[string]bool { r, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) if err != nil { return nil } ssMap := make(map[string]bool) for _, f := range r.File { if x := strings.Index(f.Name, "LC_MESSAGES"); x != -1 { s := strings.TrimRight(f.Name[:x], `\/`) if x = strings.LastIndexAny(s, `\/`); x != -1 { s = s[x+1:] } if s != "" { ssMap[s] = true } continue } if x := strings.Index(f.Name, "LC_RESOURCE"); x != -1 { s := strings.TrimRight(f.Name[:x], `\/`) if x = strings.LastIndexAny(s, `\/`); x != -1 { s = s[x+1:] } if s != "" { ssMap[s] = true } continue } } return ssMap }
// LastIndexAny returns the index of the last instance of any Unicode code // point from chars in s, or -1 if no Unicode code point from chars is present in s func LastIndexAny(s, chars string) int { fmt.Println(strings.LastIndexAny("gogopher", "go")) // 3 fmt.Println(strings.LastIndexAny("gogopher", "ogh")) // 5 fmt.Println(strings.LastIndexAny("gogopher", "gr")) // 7 fmt.Println(strings.LastIndexAny("gogopher", "rodent")) // 7 return strings.LastIndexAny(s, chars) }
func (cp ContainerPort) GetContainerPort() string { start := strings.LastIndexAny(string(cp), Host_Container_Separator) + 1 end := strings.LastIndexAny(string(cp), Port_Protocol_Separator) if end == -1 { end = len(string(cp)) } return string(cp)[start:end] }
// 获取上一层目录 func GetPreDir(dir string) string { dir3 := "" if runtime.GOOS == "windows" { dir2 := strings.LastIndexAny(dir, "\\") dir3 = dir[:dir2] + "\\" } else { dir2 := strings.LastIndexAny(dir, "/") dir3 = dir[:dir2] + "/" } return dir3 }
func (pb *PortBinding) parseContainerPort(portStr string) error { start := strings.LastIndexAny(portStr, ":") + 1 end := strings.LastIndexAny(portStr, "/") if end == -1 { end = len(portStr) } cPort, err := strconv.ParseUint(portStr[start:end], 10, 32) if err != nil { return errors.New(fmt.Sprintf("Can not parse container port. %s", portStr)) } pb.ContainerPort = int(cPort) return nil }
func (this *Rotator) Create(name string, rotationByTime int) { if name[len(name)-1] == '\\' || name[len(name)-1] == '/' { this.baseFileName = name + "default.log" } else { this.baseFileName = name } if strings.LastIndexAny(name, "\\/") != -1 { os.MkdirAll(name[0:strings.LastIndexAny(name, "\\/")], 0766) } // fmt.Println("name:", name) this.rotationByTime = rotationByTime now := time.Now() this.switchFile(now) }
func formatNotes(notes []*profile.Note, width int) []string { if len(notes) == 0 { return []string{""} } var output []string for _, v := range notes { text := fmt.Sprintf("%s | %s", v.Title, v.Text) for _, line := range strings.Split(text, "\n") { if len(line) <= width { output = append(output, line) continue } rem := line for { if len(rem) <= width { output = append(output, rem) break } cur := rem[:width] if p := strings.LastIndexAny(cur, " ,."); p > width/2 { cur = cur[:p+1] } output = append(output, cur) rem = rem[len(cur):] } } } return output }
func main() { fmt.Println(strings.Index("Hello, world!", "He")) // 0: He가 맨 처음에 있으므로 0 fmt.Println(strings.Index("Hello, world!", "wor")) // 7: wor가 8번째에 있으므로 7 fmt.Println(strings.Index("Hello, world!", "ow")) // -1: ow는 없으므로 -1 fmt.Println(strings.IndexAny("Hello, world!", "eo")) // 1: e가 2번째에 있으므로 1 fmt.Println(strings.IndexAny("Hello, world!", "f")) // -1: f는 없으므로 -1 var c byte c = 'd' fmt.Println(strings.IndexByte("Hello, world!", c)) // 11: d가 12번째에 있으므로 11 c = 'f' fmt.Println(strings.IndexByte("Hello, world!", c)) // -1: f는 없으므로 -1 var r rune r = '언' fmt.Println(strings.IndexRune("고 언어", r)) // 4: "언"이 시작되는 인덱스가 4 f := func(r rune) bool { return unicode.Is(unicode.Hangul, r) // r이 한글 유니코드이면 true를 리턴 } fmt.Println(strings.IndexFunc("Go 언어", f)) // 3: 한글이 4번째부터 시작하므로 3 fmt.Println(strings.IndexFunc("Go Language", f)) // -1: 한글이 없으므로 -1 fmt.Println(strings.LastIndex("Hello Hello Hello, world!", "Hello")) // 12: 마지막 Hello가 13번째에 있으므로 12 fmt.Println(strings.LastIndexAny("Hello, world", "ol")) // 10: 마지막 l이 11번째에 있으므로 10 fmt.Println(strings.LastIndexFunc("Go 언어 안녕", f)) // 13: 마지막 한글인 '녕'이 시작되는 인덱스가 13 }
// basename for Windows and Unix (strips everything before / or \\ func BaseName(fn string) string { p := strings.LastIndexAny(fn, `/\`) if p >= 0 { fn = fn[p+1:] } return fn }
func hasExt(file string) bool { i := strings.LastIndex(file, ".") if i < 0 { return false } return strings.LastIndexAny(file, `:\/`) < i }
func (t *Thermometer) getTemperature() float64 { path := t.device + "/w1_slave" file, err := os.Open(path) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) var lines []string for scanner.Scan() { lines = append(lines, scanner.Text()) } statusLine := lines[0] statusLineLen := len(statusLine) if statusLineLen < 3 || statusLine[statusLineLen-3:] != "YES" { log.Fatal("Temperature doesn't seem to be valid") } dataLine := lines[1] l := strings.LastIndexAny(dataLine, "t=") celsius, err := strconv.ParseFloat(dataLine[l+1:], 64) if err != nil { log.Fatal("Could not convert temperature from device") } return (celsius / 1000.0) }
func (w *PkgWalker) LookupImport(pkg *types.Package, pkgInfo *types.Info, cursor *FileCursor, is *ast.ImportSpec) { fpath, err := strconv.Unquote(is.Path.Value) if err != nil { return } fbase := fpath pos := strings.LastIndexAny(fpath, "./-\\") if pos != -1 { fbase = fpath[pos+1:] } fid := fpath + "." + fbase //kind := ObjPkgName //fmt.Println(kind, true) if typeFindDef { fmt.Println(w.fset.Position(is.Pos())) } if typeFindInfo { fmt.Println("package", fpath) } if !typeFindUse { return } var usages []int for id, obj := range pkgInfo.Uses { if obj != nil && obj.Id() == fid { //!= nil && cursorObj.Pos() == obj.Pos() { usages = append(usages, int(id.Pos())) } } (sort.IntSlice(usages)).Sort() for _, pos := range usages { fmt.Println(w.fset.Position(token.Pos(pos))) } }
func zhihuDailyJson(str string) UsedData { sj, _ := simplejson.NewJson([]byte(str)) tmp, _ := time.Parse("20060102", sj.Get("date").MustString()) date := tmp.Format("2006.01.02 Monday") news, _ := sj.Get("news").Array() var mainpages []MainPage var shareimageurl, shareimage, title string for _, a := range news { m := a.(map[string]interface{}) url := m["url"].(string) id := atoi(url[strings.LastIndexAny(url, "/")+1:]) if m["share_image"] != nil { shareimageurl = m["share_image"].(string) } else { // new api do not provide share_imag title = m["title"].(string) shareimageurl = m["image"].(string) } shareimage = shareImgUrlToFilename(shareimageurl) mainpages = append(mainpages, MainPage{id, title, shareimage}) } return UsedData{Date: date, MainPages: mainpages} }
// dir makes a good-faith attempt to return the directory // portion of path. If path is empty, the result is ".". // (Per the go/build package dependency tests, we cannot import // path/filepath and simply use filepath.Dir.) func dir(path string) string { if i := strings.LastIndexAny(path, `/\`); i > 0 { return path[:i] } // i <= 0 return "." }
// replaceWithToneMark returns the UTF-8 representation of a pinyin syllable with // the appropriate tone, e.g., dong1 => dōng, using the pinyin accent placement rules func replaceWithToneMark(s string, tone int) (string, error) { lookup, err := toneLookupTable(tone) if err != nil { return "", err } if strings.Contains(s, "a") { return strings.Replace(s, "a", lookup["a"], -1), nil } if strings.Contains(s, "e") { return strings.Replace(s, "e", lookup["e"], -1), nil } if strings.Contains(s, "ou") { return strings.Replace(s, "o", lookup["o"], -1), nil } index := strings.LastIndexAny(s, "iüou") if index != -1 { var out bytes.Buffer for ind, runeValue := range s { if ind == index { out.WriteString(lookup[string(runeValue)]) } else { out.WriteString(string(runeValue)) } } return out.String(), nil } return "", fmt.Errorf("No tone match") }
func byteSizeFromString(arg string) (int64, error) { digits := "" rest := "" last := strings.LastIndexAny(arg, "0123456789") if last >= 0 { digits = arg[:last+1] rest = arg[last+1:] } val, err := strconv.ParseInt(digits, 10, 64) if err != nil { return val, err } rest = strings.ToLower(strings.TrimSpace(rest)) var multiplier int64 = 1 switch rest { case "": multiplier = 1 case "k", "kb": multiplier = 1024 case "m", "mb": multiplier = 1024 * 1024 case "g", "gb": multiplier = 1024 * 1024 * 1024 case "t", "tb": multiplier = 1024 * 1024 * 1024 * 1024 default: return 0, fmt.Errorf("Unknown size unit: %s", rest) } return val * multiplier, nil }
// modGoBooleans modifies the basic golang function so that it uses bool rather // than GL_TRUE and GL_FALSE. This inserts a codeblock for each boolean parameter // and updates the parameters lists to match. No changes are made if no bool parms. func modGoBooleans(goapi string) string { btoks := strings.Split(goapi, ") bool") if len(btoks) == 1 { btoks := strings.Split(goapi, " bool") if len(btoks) > 1 { // process each boolean parameter for cnt := 0; cnt < len(btoks)-1; cnt++ { btok := strings.TrimSpace(btoks[cnt]) startTrim := strings.LastIndexAny(btok, "( ") tag := btok[startTrim+1 : len(btok)] // create the code block cb := fmt.Sprintf("tf%d", cnt+1) insert := "{ \n" + " %s := FALSE\n" + " if %s {\n" + " %s = TRUE\n" + " }" insert = fmt.Sprintf(insert, cb, tag, cb) // insert the code block parts := strings.Split(goapi, "{ ") goapi = fmt.Sprintf("%s %s %s", parts[0], insert, parts[1]) replace := fmt.Sprintf("C.uchar(%s)", tag) with := fmt.Sprintf("C.uchar(%s)", cb) goapi = strings.Replace(goapi, replace, with, 1) } } } return goapi }
// 写每一个*.dat数据 func write(infile string, sheet *xlsx.Sheet, rawNbr int) { fmt.Println("正在处理", infile) var id int start := strings.LastIndexAny(infile, "\\") id, _ = strconv.Atoi(infile[start+1 : len(infile)-4]) fmt.Println(id) var cell *xlsx.Cell var row *xlsx.Row file, err := os.Open(infile) if err != nil { fmt.Println("Failed to open the input file ", infile) return } defer file.Close() br := bufio.NewReader(file) var indexi int = 0 _, _, _ = br.ReadLine() for { line, isPrefix, err1 := br.ReadLine() if err1 != nil { if err1 != io.EOF { err = err1 } break } if isPrefix { fmt.Println("A too long line, seems unexpected.") return } str := string(line) // Convert []byte to string if len(str) < 5 { break } split := str[1 : len(str)-1] array := strings.Split(split, ",") row = sheet.AddRow() cell = row.AddCell() cell.SetInt(id) indexi = 0 for _, v := range array { if indexi >= rawNbr-1 { break } indexi = indexi + 1 cell = row.AddCell() value, _ := strconv.Atoi(v) cell.SetInt(value) } } return }
func (p *Parser) parseStream(reader io.Reader) { var node *Node lineNumber := 0 lineScanner := bufio.NewScanner(reader) for lineScanner.Scan() { lineNumber++ line := lineScanner.Text() trimmedLine := mytrim(line) //skip empty lines and lines starting with # if trimmedLine == "" || line[0] == p.parserOptions.commentChar { continue } //new nodes start at the beginning of the line if line[0] != runeSpace && line[0] != runeTab { if node != nil { p.nodes <- node } node = NewNode(trimmedLine) continue } if node != nil { separator := strings.LastIndexAny(trimmedLine, "\t ") if separator == -1 { p.errors <- NewBreakingError( fmt.Sprintf("Bad syntax on line %d, \"%s\".", lineNumber, line), exitErrorBadSyntax, ) return } ename := mytrim(trimmedLine[0:separator]) //get element value snum := mytrim(trimmedLine[separator:]) enum, err := strconv.ParseFloat(snum, 32) if err != nil { p.errors <- NewBreakingError( fmt.Sprintf("Error converting \"%s\" to float on line %d \"%s\".", snum, lineNumber, line), exitErrorConversion, ) return } if ndx, exists := node.elements.index(ename); exists { (*node.elements)[ndx].val += float32(enum) } else { node.elements.add(ename, float32(enum)) } } } // push last node if node != nil { p.nodes <- node } p.done <- true }
func (cp ContainerPort) GetContainerProtocol() string { protcIdx := strings.LastIndexAny(string(cp), Port_Protocol_Separator) if protcIdx > 0 { return string(cp)[protcIdx+1:] } else { return Default_Container_Protocol } }
func (pb *PortBinding) parstProtocal(portStr string) { protcIdx := strings.LastIndexAny(portStr, "/") if protcIdx > 0 { pb.Protocal = portStr[protcIdx+1:] } else { pb.Protocal = "tcp" } }
func TestLastIndexAny(t *testing.T) { for _, tc := range lastIndexAnyTests { actual := strings.LastIndexAny(tc.s, tc.chars) if actual != tc.out { t.Errorf("strings.LastIndexAny(%q, %q) = %v; want %v", tc.s, tc.chars, actual, tc.out) } } }
func (cp ContainerPort) GetHostPort() string { end := strings.LastIndexAny(string(cp), Host_Container_Separator) if end <= 0 { return "" } hp := string(cp)[0:end] return hp }
// 从左数起直到最后一个分隔符的字符串 // 例如:trip_to("123_456_789", '_') = 123_456 func trip_to(str *string, delimiter string) string { var n int = strings.LastIndexAny(*str, delimiter) if n <= 0 { return *str } return (*str)[0 : n-1] }
// SplitOrigin splits a snappy name name into a (name, origin) pair func SplitOrigin(name string) (string, string) { idx := strings.LastIndexAny(name, ".") if idx > -1 { return name[:idx], name[idx+1:] } return name, "" }
func (data *FileData) ImgName() string { imgName := data.LocalUrl if strings.ContainsAny(imgName, "/\\:") { i := strings.LastIndexAny(imgName, "/\\:") runes := []rune(imgName) imgName = string(runes[i+1:]) } return time.Now().Format(IMG_PRE_FMT) + imgName }
// dir makes a good-faith attempt to return the directory // portion of path. If path is empty, the result is ".". // (Per the go/build package dependency tests, we cannot import // path/filepath and simply use filepath.Dir.) func dir(path string) string { if i := strings.LastIndexAny(path, "/\\"); i >= 0 { path = path[:i] } if path == "" { path = "." } return path }
//Functions for displaying information func o_() string { pc, _, _, _ := runtime.Caller(1) name := runtime.FuncForPC(pc).Name() if p := strings.LastIndexAny(name, `./\`); p >= 0 { name = name[p+1:] } // if fmt.Println("== BEGIN", name, "===") return name }
func o_(t *testing.T) (string, *testing.T) { pc, _, _, _ := runtime.Caller(1) name := runtime.FuncForPC(pc).Name() if p := strings.LastIndexAny(name, `./\`); p >= 0 { name = name[p+1:] } // if t.Logf("== BEGIN %s ==", name) return name, t }
// 移掉路径,只返回文件名称 // 例如:../../xxxx.txt -> xxxx.txt func Strip_dir(path string) string { var n int = strings.LastIndexAny(path, "/\\") if n <= 0 { return path } var n_len = len(path) return path[n-1 : n_len-1] }