当前位置: 首页>>代码示例>>Golang>>正文


Golang strings.Compare函数代码示例

本文整理汇总了Golang中strings.Compare函数的典型用法代码示例。如果您正苦于以下问题:Golang Compare函数的具体用法?Golang Compare怎么用?Golang Compare使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Compare函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Merge

// Merge Intervals results
func (intervals *Intervals) Merge() {
	merged := make([]Interval, 0)

	for _, value := range intervals.List {
		// Markers
		intervalExists := false
		atInterval := 0

		// Check that Interval already exists in merged
		for mIndex, mValue := range merged {
			compareStart := strings.Compare(value.Start, mValue.Start)
			compareEnd := strings.Compare(value.End, mValue.End)

			if compareStart == 0 && compareEnd == 0 {
				intervalExists = true
				atInterval = mIndex
			}
		}

		// Add to existing value
		if intervalExists {
			merged[atInterval].Total += value.Total
			merged[atInterval].Unique += value.Unique
		} else {
			// Or append to merged
			merged = append(merged, value)
		}
	}

	// Set intervals.List to merged
	intervals.List = merged
}
开发者ID:GitbookIO,项目名称:micro-analytics,代码行数:33,代码来源:types.go

示例2: command

func command(args []string) {
	err := errors.New("No error")
	com := ""
	com_num := 0
	for _, arg := range args {
		fmt.Println(arg)
		if strings.Compare(com, "registe") == 0 {
			if com_num == 0 {
				fmt.Println("got one")
				persons[num].Name = arg
			} else {
				persons[num].Age, err = strconv.Atoi(arg)
				if err != nil {
					fmt.Println("Error: ", err)
				}
				num = num + 1
				com = "no"
			}
		}
		if strings.Compare(com, "list") == 0 {
			fmt.Println("Go another one")
			fmt.Println("num: ", num)
			for i := 0; i < num; i++ {
				fmt.Println("Name: ", persons[i].Name, "\tAge: ", persons[i].Age)
			}
		}
		if strings.Compare(com, "") == 0 {
			com = arg
		}
	}
}
开发者ID:gogeof,项目名称:myTest,代码行数:31,代码来源:main.go

示例3: Action

func Action(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	r.ParseForm()
	action := mytypes.Action{}
	if 1 != len(r.Form) {
		fmt.Fprintf(w, "{\"status\":false}")
		return
	}
	for key, _ := range r.Form {
		err := json.Unmarshal([]byte(key), &action)
		if err != nil {
			fmt.Fprintf(w, "{\"status\":false}")
			return
		}

		// Action: start/stop
		for k, v := range action {
			if 0 == strings.Compare(k, "action") && (0 == strings.Compare(v, "start") || 0 == strings.Compare(v, "stop")) {
				// e.Set(k, v)
				log.Print("Key: ", k, ", Value: ", v)
				break
			} else {
				fmt.Fprintf(w, "{\"status\":false}")
				return
			}
		}
	} // for key
	fmt.Fprintf(w, "{\"status\":true")
}
开发者ID:lth2015,项目名称:esbeat,代码行数:28,代码来源:http.go

示例4: Validate

func (am AllMetadata) Validate() error {
	if am == nil || len(am) == 0 {
		return ErrValidatingData
	}

	// check some required fields
	var deviceType interface{}
	var imageID interface{}

	for k, v := range am {
		if v == nil {
			return ErrValidatingData
		}
		if strings.Compare(k, "deviceType") == 0 {
			deviceType = v
		}
		if strings.Compare(k, "imageId") == 0 {
			imageID = v
		}
	}
	if deviceType == nil || imageID == nil {
		return ErrValidatingData
	}
	return nil
}
开发者ID:pasinskim,项目名称:mender,代码行数:25,代码来源:metadata.go

示例5: PbrtTexture

func PbrtTexture(name string, textype string, texname string, params *ParamSet) {
	VERIFY_WORLD("Texture")
	tp := CreateTextureParams(params, params, graphicsState.floatTextures, graphicsState.spectrumTextures)
	if strings.Compare(textype, "float") == 0 {
		// Create _float_ texture and store in _floatTextures_
		if graphicsState.floatTextures[name] != nil {
			Info("Texture \"%s\" being redefined", name)
		}
		WARN_IF_ANIMATED_TRANSFORM("Texture")
		ft := MakeFloatTexture(texname, curTransform.t[0], tp)
		if ft != nil {
			graphicsState.floatTextures[name] = ft
		}
	} else if strings.Compare(textype, "color") == 0 || strings.Compare(textype, "spectrum") == 0 {
		// Create _color_ texture and store in _spectrumTextures_
		if graphicsState.spectrumTextures[name] != nil {
			Info("Texture \"%s\" being redefined", name)
		}
		WARN_IF_ANIMATED_TRANSFORM("Texture")
		st := MakeSpectrumTexture(texname, curTransform.t[0], tp)
		if st != nil {
			graphicsState.spectrumTextures[name] = st
		}
	} else {
		Error("Texture type \"%s\" unknown.", textype)
	}
}
开发者ID:rweyrauch,项目名称:gopbrt,代码行数:27,代码来源:api.go

示例6: webhookHandler

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	// Always reeturn text/plain OK with a 200 to obscure that this actually is.
	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "OK")

	log.Printf("Webhook Request: %s Path: %s RemoteAddr: %s UserAgent: %s\n", r.Method, r.URL.Path, r.RemoteAddr, r.UserAgent())
	if strings.Compare(r.Method, "POST") == 0 {
		header := r.Header
		contentType := header.Get("Content-Type")
		xGithubSignature := header.Get("X-Hub-Signature")
		if strings.Compare(contentType, "application/json") == 0 && xGithubSignature != "" {
			body, err := ioutil.ReadAll(r.Body)
			if err == nil && verifySignature([]byte(webhookSecret), xGithubSignature, body) == true {
				log.Printf("Webhook validated, running %q", webhookCommand)
				out, err := exec.Command(webhookCommand).Output()
				if err != nil {
					log.Printf("Webhook error: %s", err)
					return
				}
				log.Printf("Webhook out: %s", out)
				return
			}
		}
	}
	log.Printf("Webhook invalid request method.")
	return
}
开发者ID:caltechlibrary,项目名称:cait,代码行数:28,代码来源:servepages.go

示例7: TestGetMongoNormal

func TestGetMongoNormal(t *testing.T) {
	var data = `
  development:
    mongo:
      port: 27017
      host: mongo
      database: test
      credential:
        username: lunarc
        password: lunarc
  `
	mongo, err := GetMongo([]byte(data), "development")
	if err != nil {
		t.Fatalf("Non expected error %v", err)
	}
	if mongo.Port != 27017 {
		t.Fatalf("Must return a Mongo with Port 27017 not %v", mongo.Port)
	}
	if strings.Compare(mongo.Host, "mongo") != 0 {
		t.Fatalf("Must return a Mongo with Host mongo not %v", mongo.Host)
	}
	if strings.Compare(mongo.Database, "test") != 0 {
		t.Fatalf("Must return a Mongo with Database mongo not %v", mongo.Database)
	}
	if strings.Compare(mongo.Credential.Username, "lunarc") != 0 {
		t.Fatalf("Must return a Mongo with username credential lunarc not %v", mongo.Credential.Username)
	}
	if strings.Compare(mongo.Credential.Password, "lunarc") != 0 {
		t.Fatalf("Must return a Mongo with password credential lunarc not %v", mongo.Credential.Password)
	}
}
开发者ID:DamienFontaine,项目名称:lunarc,代码行数:31,代码来源:mongo_test.go

示例8: ParseHeader

func (rp *RootfsParser) ParseHeader(tr *tar.Reader, hdr *tar.Header, hPath string) error {
	relPath, err := filepath.Rel(hPath, hdr.Name)
	if err != nil {
		return err
	}

	switch {
	case strings.Compare(relPath, "files") == 0:
		if rp.updates == nil {
			rp.updates = map[string]UpdateFile{}
		}
		if err = parseFiles(tr, rp.updates); err != nil {
			return err
		}
	case strings.Compare(relPath, "type-info") == 0:
		// we can skip this one for now
	case strings.Compare(relPath, "meta-data") == 0:
		if _, err = io.Copy(&rp.metadata, tr); err != nil {
			return errors.Wrapf(err, "parser: error reading metadata")
		}
	case strings.HasPrefix(relPath, "checksums"):
		if err = processChecksums(tr, hdr.Name, rp.updates); err != nil {
			return err
		}
	case strings.HasPrefix(relPath, "signatures"):
		//TODO:
	case strings.HasPrefix(relPath, "scripts"):
		//TODO

	default:
		return errors.New("parser: unsupported element '" + relPath + "' in header")
	}
	return nil
}
开发者ID:pasinskim,项目名称:mender,代码行数:34,代码来源:rootfs_parser.go

示例9: testIt

func testIt(rawStr string) {
	log.Printf("*** %s ***\n", rawStr)
	xiaBase64Encode := string(xiaBase64.Encode([]byte(rawStr)))
	stdBase64Encode := base64.StdEncoding.EncodeToString([]byte(rawStr))
	if strings.Compare(xiaBase64Encode, stdBase64Encode) != 0 {
		log.Println("xiaBase64Encode is wrong!")
		log.Printf("xia: %s , std: %s", xiaBase64Encode, stdBase64Encode)
		return
	}
	log.Println("xiaBase64Encode is right!")

	xiaBase64Decode, err := xiaBase64.Decode([]byte(xiaBase64Encode))
	if err != nil {
		log.Fatalln(err)
		return
	}
	stdBase64Decode, err := base64.StdEncoding.DecodeString(xiaBase64Encode)
	if err != nil {
		log.Fatalln(err)
	}
	if strings.Compare(string(xiaBase64Decode), string(stdBase64Decode)) != 0 {
		log.Println("xiaBase64Decode is wrong!")
		log.Printf("xia: %s , std: %s", xiaBase64Decode, stdBase64Decode)
		return
	}
	log.Println("xiaBase64Decode is right!")
}
开发者ID:youngsterxyf,项目名称:xiaBase64,代码行数:27,代码来源:test.go

示例10: CreateBilerpSpectrumTexture

func CreateBilerpSpectrumTexture(tex2world *Transform, tp *TextureParams) *BilerpTextureSpectrum {
	// Initialize 2D texture mapping _map_ from _tp_
	var mapping TextureMapping2D
	maptype := tp.FindString("mapping", "uv")
	if strings.Compare(maptype, "uv") == 0 {
		su := tp.FindFloat("uscale", 1.0)
		sv := tp.FindFloat("vscale", 1.0)
		du := tp.FindFloat("udelta", 0.0)
		dv := tp.FindFloat("vdelta", 0.0)
		mapping = NewUVMapping2D(su, sv, du, dv)
	} else if strings.Compare(maptype, "spherical") == 0 {
		mapping = NewSphericalMapping2D(InverseTransform(tex2world))
	} else if strings.Compare(maptype, "cylindrical") == 0 {
		mapping = NewCylindricalMapping2D(InverseTransform(tex2world))
	} else if strings.Compare(maptype, "planar") == 0 {
		mapping = NewPlanarMapping2D(tp.FindVector("v1", Vector{1, 0, 0}),
			tp.FindVector("v2", Vector{0, 1, 0}),
			tp.FindFloat("udelta", 0.0), tp.FindFloat("vdelta", 0.0))
	} else {
		Error("2D texture mapping \"%s\" unknown", maptype)
		mapping = NewUVMapping2D(1, 1, 0, 0)
	}
	return NewBilerpTextureSpectrum(mapping,
		tp.FindSpectrum("v00", *NewSpectrum1(0)), tp.FindSpectrum("v01", *NewSpectrum1(1)),
		tp.FindSpectrum("v10", *NewSpectrum1(0)), tp.FindSpectrum("v11", *NewSpectrum1(1)))
}
开发者ID:rweyrauch,项目名称:gopbrt,代码行数:26,代码来源:creators.go

示例11: ParseHeader

func (rp *GenericParser) ParseHeader(tr *tar.Reader, hdr *tar.Header, hPath string) error {
	relPath, err := filepath.Rel(hPath, hdr.Name)
	if err != nil {
		return err
	}

	switch {
	case strings.Compare(relPath, "files") == 0:
		if rp.updates == nil {
			rp.updates = map[string]UpdateFile{}
		}
		if err = parseFiles(tr, rp.updates); err != nil {
			return err
		}
	case strings.Compare(relPath, "meta-data") == 0:
		if _, err = io.Copy(&rp.metadata, tr); err != nil {
			return errors.Wrapf(err, "parser: error reading metadata")
		}
	case strings.HasPrefix(relPath, "checksums"):
		if err = processChecksums(tr, hdr.Name, rp.updates); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:pasinskim,项目名称:mender,代码行数:25,代码来源:generic_parser.go

示例12: NextPacket

//NextPacket Get one packet from Decoder. At the end of file,
//get error io.EOF with nil field.
func (d *Decoder) NextPacket() (field *Field, err error) {
	var out []byte
	var startRecord = false

	for {
		line, _, err := d.bufioReader.ReadLine()
		if err == io.EOF {
			return field, err
		} else if err != nil {
			return field, err
		}

		if strings.Compare(string(line), "<packet>") == 0 {
			startRecord = true
		}

		if startRecord {
			out = append(out, line...)
			out = append(out, byte('\n'))

			if strings.Compare(string(line), "</packet>") == 0 {
				break
			}
		}
	}

	r := bytes.NewReader(out)
	field, err = d.LoadPacket(r)
	if err != nil {
		return field, err
	}

	return
}
开发者ID:sunwxg,项目名称:goshark,代码行数:36,代码来源:goshark.go

示例13: Test_cache_get

func Test_cache_get(t *testing.T) {
	test_name := "Test_cache_get"
	setup_test_dir_cache(test_name)

	// create a file, and read it via the cache

	test_filename := "test.txt"
	test_bytes := []byte("This is a test file.")
	test_type := "text/plain"

	f, _ := _mkfile(test_filename)
	f.Write(test_bytes)
	f.Close()

	cache_init(default_timeout_ms)
	content_map_init()
	i, err := cache_get(test_filename)
	if err != nil {
		t.Errorf("error getting %s from the cache\n", test_filename)
		t.Errorf("%v", err)
	}

	if strings.Compare(i.Path, test_filename) != 0 {
		t.Errorf("Path:  expected '%s' but got '%s'\n", test_filename, i.Path)
	}

	if strings.Compare(i.Type, test_type) != 0 {
		t.Errorf("Type:  expected '%s' but got '%s'\n", test_type, i.Type)
	}

	if !bytes.Equal(i.Data, test_bytes) {
		t.Errorf("Data:  i.Data does not match test_bytes\n")
	}
}
开发者ID:reganm,项目名称:web,代码行数:34,代码来源:cache_test.go

示例14: TestFormatOutput

func TestFormatOutput(t *testing.T) {
	n := NewPomodoro()

	n.Active = true

	_, n.Start = FormatDate(2015, time.January, 1, 0, 0)
	SetPomodoroDuration(n)

	expected := []string{"active", "Jan 01 2015 at 00:00:01.000", "Jan 01 2015 at 00:25:01.000"}
	got := FormatOutput(n)

	for i := 0; i < len(got); i++ {
		if strings.Compare(expected[i], got[i]) != 0 {
			t.Fail()
			t.Log(strings.Compare(expected[i], got[i]))
		}
		t.Log("\nExpected:", expected[i], "\nReceived:", got[i])
	}

	// Dont test this anymore, since it's effectively useless
	if len(expected) != len(got) {
		t.Fail()
		t.Log("\n Expected:", len(expected), "but got:", len(got))
	}
}
开发者ID:LadyDascalie,项目名称:termodoro,代码行数:25,代码来源:pomodoro_test.go

示例15: quickSort

func quickSort(array []KeyValue, left int, right int) {
	if left >= right {
		return
	}
	tmp := array[left].Key
	tmp_value := array[left].Value
	low := left
	high := right
	for low < high {
		for strings.Compare(array[high].Key, tmp) >= 0 && low < high {
			high--
		}
		array[low].Key = array[high].Key
		array[low].Value = array[high].Value
		for strings.Compare(array[low].Key, tmp) <= 0 && low < high {
			low++
		}
		array[high].Key = array[low].Key
		array[high].Value = array[low].Value
	}
	array[low].Key = tmp
	array[low].Value = tmp_value
	quickSort(array, left, low-1)
	quickSort(array, low+1, right)
}
开发者ID:samfu1994,项目名称:6.824,代码行数:25,代码来源:test_haofu.go


注:本文中的strings.Compare函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。