本文整理汇总了Golang中github.com/Unknwon/com.ToStr函数的典型用法代码示例。如果您正苦于以下问题:Golang ToStr函数的具体用法?Golang ToStr怎么用?Golang ToStr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ToStr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: updateHistory
// updateHistory updates browser history.
func updateHistory(ctx *middleware.Context, id int64) {
pairs := make([]string, 1, 10)
pairs[0] = com.ToStr(id) + ":" + com.ToStr(time.Now().UTC().Unix())
count := 0
for _, pair := range strings.Split(ctx.GetCookie("user_history"), "|") {
infos := strings.Split(pair, ":")
if len(infos) != 2 {
continue
}
pid := com.StrTo(infos[0]).MustInt64()
if pid == 0 || pid == id {
continue
}
pairs = append(pairs, pair)
count++
if count == 9 {
break
}
}
ctx.SetCookie("user_history", strings.Join(pairs, "|"), 9999999)
}
示例2: GetUserIssueStats
// GetUserIssueStats returns issue statistic information for dashboard by given conditions.
func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int) *IssueStats {
stats := &IssueStats{}
issue := new(Issue)
stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)
queryStr := "SELECT COUNT(*) FROM `issue` "
baseCond := " WHERE issue.is_closed=?"
if repoID > 0 {
baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
} else {
baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
}
switch filterMode {
case FM_ASSIGN:
baseCond += " AND assignee_id=" + com.ToStr(uid)
case FM_CREATE:
baseCond += " AND poster_id=" + com.ToStr(uid)
}
results, _ := x.Query(queryStr+baseCond, false)
stats.OpenCount = parseCountResult(results)
results, _ = x.Query(queryStr+baseCond, true)
stats.ClosedCount = parseCountResult(results)
return stats
}
示例3: DeleteWikiPage
func (repo *Repository) DeleteWikiPage(doer *User, title string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
localPath := repo.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = repo.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
title = ToWikiPageName(title)
filename := path.Join(localPath, title+".md")
os.Remove(filename)
message := "Delete page '" + title + "'"
if err = git.AddChanges(localPath, true); err != nil {
return fmt.Errorf("AddChanges: %v", err)
} else if err = git.CommitChanges(localPath, message, doer.NewGitSig()); err != nil {
return fmt.Errorf("CommitChanges: %v", err)
} else if err = git.Push(localPath, "origin", "master"); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}
示例4: RelAvatarLink
func (u *User) RelAvatarLink() string {
defaultImgUrl := "/img/avatar_default.jpg"
if u.Id == -1 {
return defaultImgUrl
}
switch {
case u.UseCustomAvatar:
if !com.IsExist(u.CustomAvatarPath()) {
return defaultImgUrl
}
return "/avatars/" + com.ToStr(u.Id)
case setting.DisableGravatar, setting.OfflineMode:
if !com.IsExist(u.CustomAvatarPath()) {
if err := u.GenerateRandomAvatar(); err != nil {
log.Error(3, "GenerateRandomAvatar: %v", err)
}
}
return "/avatars/" + com.ToStr(u.Id)
case setting.Service.EnableCacheAvatar:
return "/avatar/" + u.Avatar
}
return setting.GravatarSource + u.Avatar
}
示例5: checkRefs
// checkRefs checks if given packages are still referencing this one.
func checkRefs(pinfo *PkgInfo) {
var buf bytes.Buffer
pinfo.RefNum = 0
refIDs := strings.Split(pinfo.RefIDs, "|")
for i := range refIDs {
if len(refIDs[i]) == 0 {
continue
}
fmt.Println(com.StrTo(refIDs[i][1:]).MustInt64())
pkg, _ := GetPkgInfoById(com.StrTo(refIDs[i][1:]).MustInt64())
if pkg == nil {
continue
}
if strings.Index(pkg.ImportIDs, "$"+com.ToStr(pinfo.ID)+"|") == -1 {
continue
}
buf.WriteString("$")
buf.WriteString(com.ToStr(pkg.ID))
buf.WriteString("|")
pinfo.RefNum++
}
pinfo.RefIDs = buf.String()
}
示例6: dumpGC
func dumpGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) {
if gcstats.NumGC > 0 {
lastPause := gcstats.Pause[0]
elapsed := time.Now().Sub(startTime)
overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100
allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()
fmt.Fprintf(w, "NumGC:%d Pause:%s Pause(Avg):%s Overhead:%3.2f%% Alloc:%s Sys:%s Alloc(Rate):%s/s Histogram:%s %s %s \n",
gcstats.NumGC,
com.ToStr(lastPause),
com.ToStr(avg(gcstats.Pause)),
overhead,
com.HumaneFileSize(memStats.Alloc),
com.HumaneFileSize(memStats.Sys),
com.HumaneFileSize(uint64(allocatedRate)),
com.ToStr(gcstats.PauseQuantiles[94]),
com.ToStr(gcstats.PauseQuantiles[98]),
com.ToStr(gcstats.PauseQuantiles[99]))
} else {
// while GC has disabled
elapsed := time.Now().Sub(startTime)
allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()
fmt.Fprintf(w, "Alloc:%s Sys:%s Alloc(Rate):%s/s\n",
com.HumaneFileSize(memStats.Alloc),
com.HumaneFileSize(memStats.Sys),
com.HumaneFileSize(uint64(allocatedRate)))
}
}
示例7: commitsByRange
func (repo *Repository) commitsByRange(id sha1, page int) (*list.List, error) {
stdout, stderr, err := com.ExecCmdDirBytes(repo.Path, "git", "log", id.String(),
"--skip="+com.ToStr((page-1)*CommitsRangeSize), "--max-count="+com.ToStr(CommitsRangeSize), prettyLogFormat)
if err != nil {
return nil, errors.New(string(stderr))
}
return parsePrettyFormatLog(repo, stdout)
}
示例8: Generate
// Generate maps CSRF to each request. If this request is a Get request, it will generate a new token.
// Additionally, depending on options set, generated tokens will be sent via Header and/or Cookie.
func Generate(options ...Options) macaron.Handler {
opt := prepareOptions(options)
return func(ctx *macaron.Context, sess session.Store) {
x := &csrf{
Secret: opt.Secret,
Header: opt.Header,
Form: opt.Form,
Cookie: opt.Cookie,
CookiePath: opt.CookiePath,
ErrorFunc: opt.ErrorFunc,
}
ctx.MapTo(x, (*CSRF)(nil))
if opt.Origin && len(ctx.Req.Header.Get("Origin")) > 0 {
return
}
x.ID = "0"
uid := sess.Get(opt.SessionKey)
if uid != nil {
switch uid.(type) {
case string:
x.ID = uid.(string)
case int:
x.ID = com.ToStr(uid)
case int64:
x.ID = com.ToStr(uid)
}
}
needsNew := false
oldUid := sess.Get(opt.oldSeesionKey)
if oldUid == nil || oldUid.(string) != x.ID {
needsNew = true
sess.Set(opt.oldSeesionKey, x.ID)
} else {
// If cookie present, map existing token, else generate a new one.
if val := ctx.GetCookie(opt.Cookie); len(val) > 0 {
// FIXME: test coverage.
x.Token = val
} else {
needsNew = true
}
}
if needsNew {
// FIXME: actionId.
x.Token = GenerateToken(x.Secret, x.ID, "POST")
}
if opt.SetCookie {
ctx.SetCookie(opt.Cookie, x.Token, 0, opt.CookiePath)
}
if opt.SetHeader {
ctx.Resp.Header().Add(opt.Header, x.Token)
}
}
}
示例9: matchSubtree
func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (Handle, bool) {
for i := 0; i < len(t.subtrees); i++ {
switch t.subtrees[i].typ {
case _PATTERN_STATIC:
if t.subtrees[i].pattern == segment {
if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
return handle, true
}
}
case _PATTERN_REGEXP:
results := t.subtrees[i].reg.FindStringSubmatch(segment)
if len(results)-1 != len(t.subtrees[i].wildcards) {
break
}
for j := 0; j < len(t.subtrees[i].wildcards); j++ {
params[t.subtrees[i].wildcards[j]] = results[j+1]
}
if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
return handle, true
}
case _PATTERN_HOLDER:
if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
params[t.subtrees[i].wildcards[0]] = segment
return handle, true
}
case _PATTERN_MATCH_ALL:
if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
params["*"+com.ToStr(globLevel)] = segment
return handle, true
}
}
}
if len(t.leaves) > 0 {
leaf := t.leaves[len(t.leaves)-1]
if leaf.typ == _PATTERN_PATH_EXT {
url = segment + "/" + url
j := strings.LastIndex(url, ".")
if j > -1 {
params[":path"] = url[:j]
params[":ext"] = url[j+1:]
} else {
params[":path"] = url
}
return leaf.handle, true
} else if leaf.typ == _PATTERN_MATCH_ALL {
params["*"] = segment + "/" + url
params["*"+com.ToStr(globLevel)] = segment + "/" + url
return leaf.handle, true
}
}
return nil, false
}
示例10: updateWikiPage
// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
if err = repo.InitWiki(); err != nil {
return fmt.Errorf("InitWiki: %v", err)
}
localPath := repo.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = repo.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
title = ToWikiPageName(title)
filename := path.Join(localPath, title+".md")
// If not a new file, show perform update not create.
if isNew {
if com.IsExist(filename) {
return ErrWikiAlreadyExist{filename}
}
} else {
os.Remove(path.Join(localPath, oldTitle+".md"))
}
// SECURITY: if new file is a symlink to non-exist critical file,
// attack content can be written to the target file (e.g. authorized_keys2)
// as a new page operation.
// So we want to make sure the symlink is removed before write anything.
// The new file we created will be in normal text format.
os.Remove(filename)
if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
return fmt.Errorf("WriteFile: %v", err)
}
if len(message) == 0 {
message = "Update page '" + title + "'"
}
if err = git.AddChanges(localPath, true); err != nil {
return fmt.Errorf("AddChanges: %v", err)
} else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
Committer: doer.NewGitSig(),
Message: message,
}); err != nil {
return fmt.Errorf("CommitChanges: %v", err)
} else if err = git.Push(localPath, "origin", "master"); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}
示例11: updateWikiPage
// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
if err = repo.InitWiki(); err != nil {
return fmt.Errorf("InitWiki: %v", err)
}
localPath := repo.LocalWikiPath()
// Discard local commits make sure even to remote when local copy exists.
if com.IsExist(localPath) {
// No need to check if nothing in the repository.
if git.IsBranchExist(localPath, "master") {
if err = git.ResetHEAD(localPath, true, "origin/master"); err != nil {
return fmt.Errorf("Reset: %v", err)
}
}
}
if err = repo.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
title = ToWikiPageName(strings.Replace(title, "/", " ", -1))
filename := path.Join(localPath, title+".md")
// If not a new file, show perform update not create.
if isNew {
if com.IsExist(filename) {
return ErrWikiAlreadyExist{filename}
}
} else {
os.Remove(path.Join(localPath, oldTitle+".md"))
}
if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
return fmt.Errorf("WriteFile: %v", err)
}
if len(message) == 0 {
message = "Update page '" + title + "'"
}
if err = git.AddChanges(localPath, true); err != nil {
return fmt.Errorf("AddChanges: %v", err)
} else if err = git.CommitChanges(localPath, message, doer.NewGitSig()); err != nil {
return fmt.Errorf("CommitChanges: %v", err)
} else if err = git.Push(localPath, "origin", "master"); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}
示例12: Put
// Put puts value into cache with key and expire time.
// If expired is 0, it lives forever.
func (c *LedisCacher) Put(key string, val interface{}, expire int64) (err error) {
if expire == 0 {
if err = c.c.Set([]byte(key), []byte(com.ToStr(val))); err != nil {
return err
}
_, err = c.c.HSet([]byte(key), defaultHSetName, []byte("0"))
return err
}
if err = c.c.SetEX([]byte(key), expire, []byte(com.ToStr(val))); err != nil {
return err
}
_, err = c.c.HSet([]byte(key), defaultHSetName, []byte(com.ToStr(time.Now().Add(time.Duration(expire)*time.Second).Unix())))
return err
}
示例13: RemoveRepository
// RemoveRepository removes repository from team of organization.
func (t *Team) RemoveRepository(repoId int64) error {
idStr := "$" + com.ToStr(repoId) + "|"
if !strings.Contains(t.RepoIds, idStr) {
return nil
}
repo, err := GetRepositoryById(repoId)
if err != nil {
return err
}
if err = repo.GetOwner(); err != nil {
return err
} else if err = t.GetMembers(); err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
t.NumRepos--
t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
sess.Rollback()
return err
}
// Remove access to team members.
for _, u := range t.Members {
auth, err := GetHighestAuthorize(t.OrgId, u.Id, repo.Id, t.Id)
if err != nil {
sess.Rollback()
return err
}
access := &Access{
UserName: u.LowerName,
RepoName: path.Join(repo.Owner.LowerName, repo.LowerName),
}
if auth == 0 {
if _, err = sess.Delete(access); err != nil {
sess.Rollback()
return fmt.Errorf("fail to delete access: %v", err)
} else if err = WatchRepo(u.Id, repo.Id, false); err != nil {
sess.Rollback()
return err
}
} else if auth < t.Authorize {
if err = addAccessWithAuthorize(sess, access, AuthorizeToAccessType(auth)); err != nil {
sess.Rollback()
return err
}
}
}
return sess.Commit()
}
示例14: init
func init() {
// Load data.
if com.IsExist("data.txt") {
data, err := ioutil.ReadFile("data.txt")
if err != nil {
log.Printf("Fail to load data file: %v", err)
os.Exit(2)
}
if len(data) == 0 {
log.Println("Data file cannot be empty")
os.Exit(2)
}
for _, line := range strings.Split(string(data), "\n") {
line := strings.TrimSpace(line)
if len(line) == 0 {
continue
}
infos := strings.Split(line, "\t")
if len(infos) < 2 {
continue
}
people = append(people, person{infos[0], infos[1]})
}
} else {
// Generate fake data.
s := rand.NewSource(int64(time.Now().Nanosecond()))
r := rand.New(s)
for i := 0; i < 100; i++ {
info := com.ToStr(r.Int())
people = append(people, person{info, info})
}
}
}
示例15: DeleteLabel
// DeleteLabel delete a label of given repository.
func DeleteLabel(repoID, labelID int64) error {
l, err := GetLabelById(labelID)
if err != nil {
if err == ErrLabelNotExist {
return nil
}
return err
}
issues, err := GetIssuesByLabel(repoID, labelID)
if err != nil {
return err
}
sess := x.NewSession()
defer sessionRelease(sess)
if err = sess.Begin(); err != nil {
return err
}
for _, issue := range issues {
issue.LabelIds = strings.Replace(issue.LabelIds, "$"+com.ToStr(labelID)+"|", "", -1)
if _, err = sess.Id(issue.ID).AllCols().Update(issue); err != nil {
return err
}
}
if _, err = sess.Delete(l); err != nil {
return err
}
return sess.Commit()
}