• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang log.Debug函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: GetPlugin

// GetPlugin attempts to find a plugin and route for the given msg input if none
// can be found, it checks the database for the last route used and gets the
// plugin for that. If there is no previously used plugin, we return
// errMissingPlugin. The bool value return indicates whether this plugin is
// different from the last plugin used by the user.
func GetPlugin(db *sqlx.DB, m *dt.Msg) (p *dt.Plugin, route string, directroute,
	followup bool, err error) {

	// Iterate through all intents to see if any plugin has been registered
	// for the route
	for _, i := range m.StructuredInput.Intents {
		route = "I_" + strings.ToLower(i)
		log.Debug("searching for route", route)
		if p = RegPlugins.Get(route); p != nil {
			// Found route. Return it
			return p, route, true, false, nil
		}
	}

	log.Debug("getting last plugin route")
	prevPlugin, prevRoute, err := m.GetLastPlugin(db)
	if err != nil && err != sql.ErrNoRows {
		return nil, "", false, false, err
	}
	if len(prevPlugin) > 0 {
		log.Debugf("found user's last plugin route: %s - %s\n",
			prevPlugin, prevRoute)
	}

	// Iterate over all command/object pairs and see if any plugin has been
	// registered for the resulting route
	eng := porter2.Stemmer
	for _, c := range m.StructuredInput.Commands {
		c = strings.ToLower(eng.Stem(c))
		for _, o := range m.StructuredInput.Objects {
			o = strings.ToLower(eng.Stem(o))
			route := "CO_" + c + "_" + o
			log.Debug("searching for route", route)
			if p = RegPlugins.Get(route); p != nil {
				// Found route. Return it
				followup := prevPlugin == p.Config.Name
				return p, route, true, followup, nil
			}
		}
	}

	// The user input didn't match any plugins. Let's see if the previous
	// route does
	if prevRoute != "" {
		if p = RegPlugins.Get(prevRoute); p != nil {
			// Prev route matches a pkg! Return it
			return p, prevRoute, false, true, nil
		}
	}

	// Sadly, if we've reached this point, we are at a loss.
	log.Debug("could not match user input to any plugin")
	return nil, "", false, false, errMissingPlugin
}
开发者ID:itsabot,项目名称:abot,代码行数:59,代码来源:plugin.go


示例2: NewMsg

// NewMsg builds a message struct with Tokens, Stems, and a Structured Input.
func NewMsg(u *dt.User, cmd string) (*dt.Msg, error) {
	tokens := TokenizeSentence(cmd)
	stems := StemTokens(tokens)
	si := ner.classifyTokens(tokens)

	// Get the intents as determined by each plugin
	for pluginID, c := range bClassifiers {
		scores, idx, _ := c.ProbScores(stems)
		log.Debug("intent score", pluginIntents[pluginID][idx],
			scores[idx])
		if scores[idx] > 0.7 {
			si.Intents = append(si.Intents,
				string(pluginIntents[pluginID][idx]))
		}
	}

	m := &dt.Msg{
		User:            u,
		Sentence:        cmd,
		Tokens:          tokens,
		Stems:           stems,
		StructuredInput: si,
	}
	if err := saveContext(db, m); err != nil {
		return nil, err
	}
	if err := addContext(db, m); err != nil {
		return nil, err
	}
	return m, nil
}
开发者ID:itsabot,项目名称:abot,代码行数:32,代码来源:message.go


示例3: isAdmin

// isAdmin ensures that the current user is an admin. We trust the scopes
// presented by the client because they're validated through HMAC in
// isLoggedIn().
func isAdmin(w http.ResponseWriter, r *http.Request) bool {
	log.Debug("validating admin")
	cookie, err := r.Cookie("scopes")
	if err == http.ErrNoCookie {
		writeErrorAuth(w, err)
		return false
	}
	if err != nil {
		writeErrorInternal(w, err)
		return false
	}
	scopes := strings.Fields(cookie.Value)
	for _, scope := range scopes {
		if scope == "admin" {
			// Confirm the admin permission has not been deleted
			// since the cookie was created by retrieving the
			// current value from the DB.
			cookie, err = r.Cookie("id")
			if err == http.ErrNoCookie {
				writeErrorAuth(w, err)
				return false
			}
			if err != nil {
				writeErrorInternal(w, err)
				return false
			}
			var admin bool
			q := `SELECT admin FROM users WHERE id=$1`
			if err = db.Get(&admin, q, cookie.Value); err != nil {
				writeErrorInternal(w, err)
				return false
			}
			if !admin {
				writeErrorAuth(w, errors.New("User is not an admin"))
				return false
			}
			log.Debug("validated admin")
			return true
		}
	}
	writeErrorAuth(w, errors.New("user is not an admin"))
	return false
}
开发者ID:itsabot,项目名称:abot,代码行数:46,代码来源:handlers.go


示例4: parseTime

// parseTime iterates through all known date formats on a normalized time
// string, using Golang's standard lib to do the heavy lifting.
//
// TODO This is a brute-force, "dumb" method of determining the time format and
// should be improved.
func parseTime(t string) (time.Time, error) {
	for _, tf := range timeFormats {
		time, err := time.Parse(tf, t)
		if err == nil {
			log.Debug("timeparse: found format", tf)
			return time, nil
		}
	}
	return time.Time{}, ErrInvalidTimeFormat
}
开发者ID:itsabot,项目名称:abot,代码行数:15,代码来源:timeparse.go


示例5: clonePrivateRepo

func clonePrivateRepo(name string, errChan chan errMsg, wg *sync.WaitGroup) {
	wg.Add(1)
	defer wg.Done()

	parts := strings.Split(name, "/")
	if len(parts) < 2 {
		errChan <- errMsg{msg: "", err: errors.New("invalid dependency path: too few parts")}
		return
	}

	// Ensure we don't delete a lower level directory
	p := filepath.Join(os.Getenv("GOPATH"), "src")
	tmp := filepath.Join(p, name)
	if len(tmp)+4 <= len(p) {
		errChan <- errMsg{msg: "", err: errors.New("invalid dependency path: too short")}
		return
	}
	if strings.Contains(tmp, "..") {
		errChan <- errMsg{msg: name, err: errors.New("invalid dependency path: contains '..'")}
		return
	}
	cmd := fmt.Sprintf("rm -rf %s", tmp)
	log.Debug("running:", cmd)
	outC, err := exec.
		Command("/bin/sh", "-c", cmd).
		CombinedOutput()
	if err != nil {
		tmp = fmt.Sprintf("failed to fetch %s\n%s", name, string(outC))
		errChan <- errMsg{msg: tmp, err: err}
		return
	}
	name = strings.Join(parts[1:], "/")
	cmd = fmt.Sprintf("git clone [email protected]:%s.git %s", name, tmp)
	log.Debug("running:", cmd)
	outC, err = exec.
		Command("/bin/sh", "-c", cmd).
		CombinedOutput()
	if err != nil {
		tmp = fmt.Sprintf("failed to fetch %s\n%s", name, string(outC))
		errChan <- errMsg{msg: tmp, err: err}
	}
}
开发者ID:itsabot,项目名称:abot,代码行数:42,代码来源:abot.go


示例6: compileAssets

// compileAssets compresses and merges assets from Abot core and all plugins on
// boot. In development, this step is repeated on each server HTTP request prior
// to serving any assets.
func compileAssets() error {
	p := filepath.Join("cmd", "compileassets.sh")
	outC, err := exec.
		Command("/bin/sh", "-c", p).
		CombinedOutput()
	if err != nil {
		log.Debug(string(outC))
		return err
	}
	return nil
}
开发者ID:itsabot,项目名称:abot,代码行数:14,代码来源:boot.go


示例7: TestParse

func TestParse(t *testing.T) {
	n := time.Now()
	// _, zone := n.Zone()
	n.Add(-6 * time.Hour)
	tests := map[string][]time.Time{
		"2pm":                []time.Time{time.Date(n.Year(), n.Month(), n.Day(), 14, 0, 0, 0, n.Location())},
		"2 am":               []time.Time{time.Date(n.Year(), n.Month(), n.Day(), 2, 0, 0, 0, n.Location())},
		"at 2 p.m.":          []time.Time{time.Date(n.Year(), n.Month(), n.Day(), 14, 0, 0, 0, n.Location())},
		"2pm tomorrow":       []time.Time{time.Date(n.Year(), n.Month(), n.Day()+1, 14, 0, 0, 0, n.Location())},
		"2am yesterday":      []time.Time{time.Date(n.Year(), n.Month(), n.Day()-1, 2, 0, 0, 0, n.Location())},
		"2 days ago":         []time.Time{time.Date(n.Year(), n.Month(), n.Day()-2, 9, 0, 0, 0, n.Location())},
		"in 3 days from now": []time.Time{time.Date(n.Year(), n.Month(), n.Day()+3, 9, 0, 0, 0, n.Location())},
		"1 week":             []time.Time{time.Date(n.Year(), n.Month(), n.Day()+7, 9, 0, 0, 0, n.Location())},
		"1 week ago":         []time.Time{time.Date(n.Year(), n.Month(), n.Day()-7, 9, 0, 0, 0, n.Location())},
		"in a year":          []time.Time{time.Date(n.Year()+1, n.Month(), n.Day(), 9, 0, 0, 0, n.Location())},
		"next year":          []time.Time{time.Date(n.Year()+1, n.Month(), n.Day(), 9, 0, 0, 0, n.Location())},
		"in 4 weeks":         []time.Time{time.Date(n.Year(), n.Month(), n.Day()+28, 9, 0, 0, 0, n.Location())},
		"later today":        []time.Time{time.Date(n.Year(), n.Month(), n.Day(), n.Hour()+6, n.Minute(), 0, 0, n.Location())},
		"a few hours":        []time.Time{time.Date(n.Year(), n.Month(), n.Day(), n.Hour()+2, n.Minute(), 0, 0, n.Location())},
		"in 30 mins":         []time.Time{time.Date(n.Year(), n.Month(), n.Day(), n.Hour(), n.Minute()+30, 0, 0, n.Location())},
		"in 2 hours":         []time.Time{time.Date(n.Year(), n.Month(), n.Day(), n.Hour()+2, n.Minute(), 0, 0, n.Location())},
		"invalid time":       []time.Time{},
		"May 2050":           []time.Time{time.Date(2050, 5, 1, 0, 0, 0, 0, n.Location())},
		"June 26 2050":       []time.Time{time.Date(2050, 6, 26, 0, 0, 0, 0, n.Location())},
		"June 26th 2050":     []time.Time{time.Date(2050, 6, 26, 0, 0, 0, 0, n.Location())},
		"at 2 tomorrow": []time.Time{
			time.Date(n.Year(), n.Month(), n.Day()+1, 2, 0, 0, 0, n.Location()),
			time.Date(n.Year(), n.Month(), n.Day()+1, 14, 0, 0, 0, n.Location()),
		},
		"now":  []time.Time{time.Date(n.Year(), n.Month(), n.Day(), n.Hour(), n.Minute(), n.Second(), n.Nanosecond(), n.Location())},
		"noon": []time.Time{time.Date(n.Year(), n.Month(), n.Day(), 12, 0, 0, 0, n.Location())},
		/*
			"2 days ago at 6PM":  []time.Time{time.Date(n.Year(), n.Month(), n.Day()-2, 18, 0, 0, 0, n.Location())},
			"12PM EST":           []time.Time{time.Date(n.Year(), n.Month(), n.Day(), 12-zone, n.Minute(), 0, 0, n.Location())},
		*/
	}
	for test, exp := range tests {
		log.Debug("test:", test)
		res := Parse(test)
		if len(res) == 0 {
			if len(exp) == 0 {
				continue
			}
			t.Fatalf("expected %q, got none", exp)
		}
		if len(exp) == 0 && len(res) > 0 {
			t.Fatalf("expected none, but got %q", res)
		}
		if !exp[0].Equal(res[0]) && exp[0].Sub(res[0]) > 2*time.Minute {
			t.Fatalf("expected %q, got %q", exp, res)
		}
	}
}
开发者ID:itsabot,项目名称:abot,代码行数:53,代码来源:timeparse_test.go


示例8: ConnectDB

// ConnectDB opens a connection to the database. The name is the name of the
// database to connect to. If empty, it defaults to the current directory's
// name.
func ConnectDB(name string) (*sqlx.DB, error) {
	if len(name) == 0 {
		dir, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		name = filepath.Base(dir)
	}
	dbConnStr := DBConnectionString(name)
	log.Debug("connecting to db")
	return sqlx.Connect("postgres", dbConnStr)
}
开发者ID:itsabot,项目名称:abot,代码行数:15,代码来源:boot.go


示例9: isValidCSRF

// isValidCSRF ensures that any forms posted to Abot are protected against
// Cross-Site Request Forgery. Without this function, Abot would be vulnerable
// to the attack because tokens are stored client-side in cookies.
func isValidCSRF(w http.ResponseWriter, r *http.Request) bool {
	// TODO look into other session-based temporary storage systems for
	// these csrf tokens to prevent hitting the database.  Whatever is
	// selected must *not* introduce an external (system) dependency like
	// memcached/Redis. Bolt might be an option.
	log.Debug("validating csrf")
	var label string
	q := `SELECT label FROM sessions
	      WHERE userid=$1 AND label='csrfToken' AND token=$2`
	cookie, err := r.Cookie("id")
	if err == http.ErrNoCookie {
		writeErrorAuth(w, err)
		return false
	}
	if err != nil {
		writeErrorInternal(w, err)
		return false
	}
	uid := cookie.Value
	cookie, err = r.Cookie("csrfToken")
	if err == http.ErrNoCookie {
		writeErrorAuth(w, err)
		return false
	}
	if err != nil {
		writeErrorInternal(w, err)
		return false
	}
	err = db.Get(&label, q, uid, cookie.Value)
	if err == sql.ErrNoRows {
		writeErrorAuth(w, errors.New("invalid CSRF token"))
		return false
	}
	if err != nil {
		writeErrorInternal(w, err)
		return false
	}
	log.Debug("validated csrf")
	return true
}
开发者ID:itsabot,项目名称:abot,代码行数:43,代码来源:handlers.go


示例10: ExtractCurrency

// ExtractCurrency returns an int64 if a currency is found, and throws an
// error if one isn't.
func ExtractCurrency(s string) (int64, error) {
	s = regexCurrency.FindString(s)
	if len(s) == 0 {
		return 0, ErrNotFound
	}
	val, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return 0, err
	}
	log.Debug("found value", val)
	// Convert parsed float into an int64 with precision of 2 decimal places
	return int64(val * 100), nil
}
开发者ID:itsabot,项目名称:abot,代码行数:15,代码来源:extract.go


示例11: Positive

// Positive returns a randomized positive response to a user message.
func Positive() string {
	n := rand.Intn(3)
	switch n {
	case 0:
		return "Great!"
	case 1:
		return "I'm glad to hear that!"
	case 2:
		return "Great to hear!"
	}
	log.Debug("positive failed to return a response")
	return ""
}
开发者ID:itsabot,项目名称:abot,代码行数:14,代码来源:language.go


示例12: trainClassifiers

// trainClassifiers trains classifiers for each plugin.
func trainClassifiers() error {
	for _, pconf := range PluginsGo {
		ss, err := fetchTrainingSentences(pconf.ID, pconf.Name)
		if err != nil {
			return err
		}

		// Assemble list of Bayesian classes from all trained intents
		// for this plugin. m is used to keep track of the classes
		// already taught to each classifier.
		m := map[string]struct{}{}
		for _, s := range ss {
			_, ok := m[s.Intent]
			if ok {
				continue
			}
			log.Debug("learning intent", s.Intent)
			m[s.Intent] = struct{}{}
			pluginIntents[s.PluginID] = append(pluginIntents[s.PluginID],
				bayesian.Class(s.Intent))
		}

		// Build classifier from complete sets of intents
		for _, s := range ss {
			intents := pluginIntents[s.PluginID]
			// Calling bayesian.NewClassifier() with 0 or 1
			// classes causes a panic.
			if len(intents) == 0 {
				break
			}
			if len(intents) == 1 {
				intents = append(intents, bayesian.Class("__no_intent"))
			}
			c := bayesian.NewClassifier(intents...)
			bClassifiers[s.PluginID] = c
		}

		// With classifiers initialized, train each of them on a
		// sentence's stems.
		for _, s := range ss {
			tokens := TokenizeSentence(s.Sentence)
			stems := StemTokens(tokens)
			c, exists := bClassifiers[s.PluginID]
			if exists {
				c.Learn(stems, bayesian.Class(s.Intent))
			}
		}
	}
	return nil
}
开发者ID:itsabot,项目名称:abot,代码行数:51,代码来源:boot.go


示例13: GetUser

// GetUser from an HTTP request.
func GetUser(db *sqlx.DB, req *Request) (*User, error) {
	u := &User{}
	u.FlexID = req.FlexID
	u.FlexIDType = req.FlexIDType
	if req.UserID == 0 {
		if req.FlexID == "" {
			return nil, ErrMissingFlexID
		}
		switch req.FlexIDType {
		case FIDTEmail, FIDTPhone, FIDTSession:
			// Do nothing
		default:
			return nil, ErrInvalidFlexIDType
		}
		log.Debug("searching for user from", req.FlexID, req.FlexIDType)
		q := `SELECT userid
		      FROM userflexids
		      WHERE flexid=$1 AND flexidtype=$2
		      ORDER BY createdat DESC`
		err := db.Get(&req.UserID, q, req.FlexID, req.FlexIDType)
		if err == sql.ErrNoRows {
			return u, nil
		}
		log.Debug("got uid", req.UserID)
		if err != nil {
			return nil, err
		}
	}
	q := `SELECT id, name, email FROM users WHERE id=$1`
	if err := db.Get(u, q, req.UserID); err != nil {
		if err == sql.ErrNoRows {
			return u, nil
		}
		return nil, err
	}
	return u, nil
}
开发者ID:itsabot,项目名称:abot,代码行数:38,代码来源:user.go


示例14: SuggestedPlace

// SuggestedPlace returns a randomized place suggestion useful for recommending
// restaurants, businesses, etc.
func SuggestedPlace(s string) string {
	n := rand.Intn(4)
	switch n {
	case 0:
		return "How does this place look? " + s
	case 1:
		return "How about " + s + "?"
	case 2:
		return "Have you been here before? " + s
	case 3:
		return "You could try this: " + s
	}
	log.Debug("suggestedPlace failed to return a response")
	return ""
}
开发者ID:itsabot,项目名称:abot,代码行数:17,代码来源:language.go


示例15: ConfusedLang

// ConfusedLang returns a randomized response signalling that Abot is confused
// or could not understand the user's request.
func ConfusedLang() string {
	n := rand.Intn(4)
	switch n {
	case 0:
		return "I'm not sure I understand you."
	case 1:
		return "I'm sorry, I don't understand that."
	case 2:
		return "Uh, what are you telling me to do?"
	case 3:
		return "What should I do?"
	}
	log.Debug("confused failed to return a response")
	return ""
}
开发者ID:itsabot,项目名称:abot,代码行数:17,代码来源:nlp.go


示例16: NiceMeetingYou

// NiceMeetingYou is used to greet the user and request signup during an
// onboarding process.
func NiceMeetingYou() string {
	n := rand.Intn(3)
	switch n {
	case 0:
		return "It's nice to meet you. If we're going to work " +
			"together, can you sign up for me here? "
	case 1:
		return "Nice meeting you. Before we take this further, can " +
			"you sign up for me here? "
	case 2:
		return "Great to meet you! Can you sign up for me here to " +
			"get started? "
	}
	log.Debug("nicemeetingyou failed to return a response")
	return ""
}
开发者ID:itsabot,项目名称:abot,代码行数:18,代码来源:language.go


示例17: Welcome

// Welcome returns a randomized "you're welcome" response to a user message.
func Welcome() string {
	n := rand.Intn(5)
	switch n {
	case 0:
		return "You're welcome!"
	case 1:
		return "Sure thing!"
	case 2:
		return "I'm happy to help!"
	case 3:
		return "My pleasure."
	case 4:
		return "Sure."
	}
	log.Debug("welcome failed to return a response")
	return ""
}
开发者ID:itsabot,项目名称:abot,代码行数:18,代码来源:language.go


示例18: sendEventsTick

func sendEventsTick(evtChan chan *dt.ScheduledEvent, t time.Time) {
	// Listen for events that need to be sent.
	go func(chan *dt.ScheduledEvent) {
		q := `UPDATE scheduledevents SET sent=TRUE WHERE id=$1`
		select {
		case evt := <-evtChan:
			log.Debug("received event")
			if smsConn == nil {
				log.Info("failed to send scheduled event (missing SMS driver). will retry.")
				return
			}
			// Send event. On error, event will be retried next
			// minute.
			if err := evt.Send(smsConn); err != nil {
				log.Info("failed to send scheduled event", err)
				return
			}
			// Update event as sent
			if _, err := db.Exec(q, evt.ID); err != nil {
				log.Info("failed to update scheduled event as sent",
					err)
				return
			}
		}
	}(evtChan)

	q := `SELECT id, content, flexid, flexidtype
		      FROM scheduledevents
		      WHERE sent=false AND sendat<=$1`
	evts := []*dt.ScheduledEvent{}
	if err := db.Select(&evts, q, time.Now()); err != nil {
		log.Info("failed to queue scheduled event", err)
		return
	}
	for _, evt := range evts {
		// Queue the event for sending
		evtChan <- evt
	}
}
开发者ID:itsabot,项目名称:abot,代码行数:39,代码来源:scheduled_event.go


示例19: Greeting

// Greeting returns a randomized greeting.
func Greeting(r *rand.Rand, name string) string {
	var n int
	if len(name) == 0 {
		n = r.Intn(3)
		switch n {
		case 0:
			return fmt.Sprintf("Hi, %s.", name)
		case 1:
			return fmt.Sprintf("Hello, %s.", name)
		case 2:
			return fmt.Sprintf("Hi there, %s.", name)
		}
	} else {
		n = r.Intn(3)
		switch n {
		case 0:
			return "Hi. How can I help you?"
		case 1:
			return "Hello. What can I do for you?"
		}
	}
	log.Debug("greeting failed to return a response")
	return ""
}
开发者ID:itsabot,项目名称:abot,代码行数:25,代码来源:language.go


示例20: ParseFromTime


//.........这里部分代码省略.........
	if closeTime {
		tme = time.Now().Round(time.Minute)
	}
	ts = append(ts, tme)

	// TODO make more efficient. Handle in switch?
	tloc := timeLocation{loc: loc}
	ctx := &TimeContext{ampm: ampmNoTime, tz: tloc}
	if strings.Contains(normalized, "AM") {
		ctx.ampm = amTime
	}
	if strings.Contains(normalized, "UTC") {
		ctx.tz.utc = true
	}
	for _, ti := range ts {
		ctx = updateContext(ctx, ti, false)
	}

	// Ensure dates are reasonable even in the absence of information.
	// e.g. 2AM should parse to the current year, not 0000
	ctx = completeContext(ctx, t)

	// Loop through a second time to apply the discovered context to each
	// time. Note that this doesn't support context switching,
	// e.g. "5PM CST or PST" or "5PM EST or 6PM PST", which is rare in
	// practice. Future versions may be adapted to support it.
	if ctx.ampm == ampmNoTime {
		halfLen := len(ts)
		// Double size of times for AM/PM
		ts = append(ts, ts...)
		for i := range ts {
			var hour int
			t := ts[i]
			if i < halfLen {
				hour = t.Hour()
			} else {
				hour = t.Hour() + 12
			}
			ts[i] = time.Date(ctx.year,
				ctx.month,
				ctx.day,
				hour,
				t.Minute(),
				t.Second(),
				t.Nanosecond(),
				ctx.tz.loc)
		}
	} else {
		for i := range ts {
			t := ts[i]
			ts[i] = time.Date(ctx.year,
				ctx.month,
				ctx.day,
				t.Hour(),
				t.Minute(),
				t.Second(),
				t.Nanosecond(),
				ctx.tz.loc)
		}
	}

	// If there's no relative transform, we're done.
	if transform.Type == transformInvalid {
		if timeEmpty {
			return []time.Time{}
		}
		if idxRel == 0 {
			return ts
		}
	}

	// Check our idxRel term for the word that preceeds it. If that's a
	// number, e.g. 2 days, then that number is our Transform. Note that
	// this doesn't handle fractional modifiers, like 2.5 days.
	if idxRel > 0 {
		val, err := strconv.Atoi(st[idxRel-1])
		if err == nil {
			transform.Transform = val
		}
	}

	// Apply the transform
	log.Debugf("timeparse: normalized %q. %+v\n", normalized, transform)
	for i := range ts {
		switch transform.Type {
		case transformYear:
			ts[i] = ts[i].AddDate(transform.Transform*transform.Multiplier, 0, 0)
		case transformMonth:
			ts[i] = ts[i].AddDate(0, transform.Multiplier*transform.Transform, 0)
		case transformDay:
			ts[i] = ts[i].AddDate(0, 0, transform.Multiplier*transform.Transform)
		case transformHour:
			ts[i] = ts[i].Add(time.Duration(transform.Transform*transform.Multiplier) * time.Hour)
		case transformMinute:
			ts[i] = ts[i].Add(time.Duration(transform.Transform*transform.Multiplier) * time.Minute)
		}
	}
	log.Debug("timeparse: parsed times", ts)
	return ts
}
开发者ID:itsabot,项目名称:abot,代码行数:101,代码来源:timeparse.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang log.Info函数代码示例发布时间:2022-05-23
下一篇:
Golang wsync.Pool类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap