예제 #1
0
//GetTasks retrieves all the tasks depending on the
//status pending or trashed or completed
func GetTasks(status string) types.Context {
	var task []types.Task
	var context types.Context
	var TaskID int
	var TaskTitle string
	var TaskContent string
	var TaskCreated time.Time
	var getTasksql string

	if status == "pending" {
		getTasksql = "select id, title, content, created_date from task where finish_date is null and is_deleted='N' order by created_date asc"
	} else if status == "deleted" {
		getTasksql = "select id, title, content, created_date from task where is_deleted='Y' order by created_date asc"
	} else if status == "completed" {
		getTasksql = "select id, title, content, created_date from task where finish_date is not null order by created_date asc"
	}

	rows, err := database.Query(getTasksql)
	if err != nil {
		fmt.Println(err)
	}
	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&TaskID, &TaskTitle, &TaskContent, &TaskCreated)
		TaskContent = strings.Replace(TaskContent, "\n", "<br>", -1)
		if err != nil {
			fmt.Println(err)
		}
		TaskCreated = TaskCreated.Local()
		a := types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20]}
		task = append(task, a)
	}
	context = types.Context{Tasks: task, Navigation: status}
	return context
}
예제 #2
0
파일: tasks.go 프로젝트: dot-Sean/Tasks
//GetTasks retrieves all the tasks depending on the
//status pending or trashed or completed
func GetTasks(status string) (types.Context, error) {
	var task []types.Task
	var context types.Context
	var TaskID int
	var TaskTitle string
	var TaskContent string
	var TaskCreated time.Time
	var TaskPriority string
	var getTasksql string

	basicSQL := "select id, title, content, created_date, priority from task "
	if status == "pending" {
		getTasksql = basicSQL + " where finish_date is null and is_deleted='N' order by priority desc, created_date asc"
	} else if status == "deleted" {
		getTasksql = basicSQL + " where is_deleted='Y' order by priority desc, created_date asc"
	} else if status == "completed" {
		getTasksql = basicSQL + " where finish_date is not null order by priority desc, created_date asc"
	}

	rows := database.query(getTasksql)
	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&TaskID, &TaskTitle, &TaskContent, &TaskCreated, &TaskPriority)
		TaskContent = string(md.Markdown([]byte(TaskContent)))
		// TaskContent = strings.Replace(TaskContent, "\n", "<br>", -1)
		if err != nil {
			log.Println(err)
		}
		TaskCreated = TaskCreated.Local()
		a := types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20], Priority: TaskPriority}
		task = append(task, a)
	}
	context = types.Context{Tasks: task, Navigation: status}
	return context, nil
}
예제 #3
0
파일: expr.go 프로젝트: wutaizeng/kapacitor
// fillScope - given a scope and reference variables, we fill the exact variables from the now, fields and tags.
func fillScope(vars *stateful.Scope, referenceVariables []string, now time.Time, fields models.Fields, tags models.Tags) error {
	for _, refVariableName := range referenceVariables {
		if refVariableName == "time" {
			vars.Set("time", now.Local())
			continue
		}

		// Support the error with tags/fields collision
		var fieldValue interface{}
		var isFieldExists bool
		var tagValue interface{}
		var isTagExists bool

		if fieldValue, isFieldExists = fields[refVariableName]; isFieldExists {
			vars.Set(refVariableName, fieldValue)
		}

		if tagValue, isTagExists = tags[refVariableName]; isTagExists {
			if isFieldExists {
				return fmt.Errorf("cannot have field and tags with same name %q", refVariableName)
			}
			vars.Set(refVariableName, tagValue)
		}
		if !isFieldExists && !isTagExists {
			if !vars.Has(refVariableName) {
				return fmt.Errorf("no field or tag exists for %s", refVariableName)
			}
		}
	}

	return nil
}
예제 #4
0
파일: db.go 프로젝트: puma007/Tasks
func GetTasks(status string) []types.Task {
	var task []types.Task
	var TaskId int
	var TaskTitle string
	var TaskContent string
	var TaskCreated time.Time
	var getTasksql string
	if status == "pending" {
		getTasksql = "select id, title, content, created_date from task where finish_date is null and is_deleted='N' order by created_date asc"
	} else if status == "trashed" {
		getTasksql = "select id, title, content, created_date from task where is_deleted='Y' order by created_date asc"
	} else if status == "complete" {
		getTasksql = "select id, title, content, created_date from task where finish_date is not null order by created_date asc"
	}

	rows, err := database.Query(getTasksql)
	if err != nil {
		fmt.Println(err)
	}
	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&TaskId, &TaskTitle, &TaskContent, &TaskCreated)
		if err != nil {
			fmt.Println(err)
		}
		TaskCreated = TaskCreated.Local()
		a := types.Task{Id: TaskId, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20]}
		task = append(task, a)
	}

	return task
}
예제 #5
0
//GetComments is used to get comments, all of them.
//We do not want 100 different pages to show tasks, we want to use as few pages as possible
//so we are going to populate everything on the damn home pages
func GetComments(username string) (map[int][]types.Comment, error) {
	commentMap := make(map[int][]types.Comment)

	var taskID int
	var comment types.Comment
	var created time.Time

	userID, err := GetUserID(username)
	if err != nil {
		return commentMap, err
	}
	stmt := "select c.id, c.taskID, c.content, c.created, u.username from comments c, task t, user u where t.id=c.taskID and c.user_id=t.user_id and t.user_id=u.id and u.id=?"
	rows := database.query(stmt, userID)

	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&comment.ID, &taskID, &comment.Content, &created, &comment.Username)
		comment.Content = string(md.Markdown([]byte(comment.Content)))
		if err != nil {
			return commentMap, err
		}
		// comment.Content = string(md.Markdown([]byte(comment.Content))) ## have to fix the <p> issue markdown support
		created = created.Local()
		comment.Created = created.Format("Jan 2 2006 15:04:05")
		commentMap[taskID] = append(commentMap[taskID], comment)
	}
	return commentMap, nil
}
예제 #6
0
파일: builds.go 프로젝트: ArthurHlt/fly
func populateTimeCells(startTime time.Time, endTime time.Time) (ui.TableCell, ui.TableCell, ui.TableCell) {
	var startTimeCell ui.TableCell
	var endTimeCell ui.TableCell
	var durationCell ui.TableCell

	startTime = startTime.Local()
	endTime = endTime.Local()
	zeroTime := time.Unix(0, 0)

	if startTime == zeroTime {
		startTimeCell.Contents = "n/a"
	} else {
		startTimeCell.Contents = startTime.Format(timeDateLayout)
	}

	if endTime == zeroTime {
		endTimeCell.Contents = "n/a"
		durationCell.Contents = fmt.Sprintf("%v+", roundSecondsOffDuration(time.Since(startTime)))
	} else {
		endTimeCell.Contents = endTime.Format(timeDateLayout)
		durationCell.Contents = endTime.Sub(startTime).String()
	}

	if startTime == zeroTime && endTime == zeroTime {
		durationCell.Contents = "n/a"
	}

	return startTimeCell, endTimeCell, durationCell
}
예제 #7
0
func (b *QueryNode) Queries(start, stop time.Time) ([]*Query, error) {
	now := time.Now()
	if stop.IsZero() {
		stop = now
	}
	// Crons are sensitive to timezones.
	// Make sure we are using local time.
	current := start.Local()
	queries := make([]*Query, 0)
	for {
		current = b.ticker.Next(current)
		if current.IsZero() || current.After(stop) {
			break
		}
		qstop := current.Add(-1 * b.b.Offset)
		if qstop.After(now) {
			break
		}

		q, err := b.query.Clone()
		if err != nil {
			return nil, err
		}
		q.SetStartTime(qstop.Add(-1 * b.b.Period))
		q.SetStopTime(qstop)
		queries = append(queries, q)
	}
	return queries, nil
}
예제 #8
0
// FormatDate converts a time.Time value to a formatted displayable datetime
func (viewHelper *ViewHelper) FormatDate(value time.Time) string {
	viewTime := value.Local().Format("2006-01-02 15:04:05")
	if viewTime == "0000-12-31 20:00:00" {
		return ""
	}

	return viewTime
}
예제 #9
0
func logInfo(trid int, sTime time.Time, msg string, params ...interface{}) {
	//timestamp spentTime peer x-real-ip method status 'request URI' message
	spew.Fprintf(os.Stderr, "Thread %d: %s %d %s\n",
		trid,
		sTime.Local().Format("2006-01-02-15-04-05.000"),
		int(time.Now().Sub(sTime).Seconds()*1000),
		spew.Sprintf(msg, params...),
	)
}
// Work out the rollover time based on the specified time.
func (self *TimedRotatingFileHandler) computeRolloverTime(
	currentTime time.Time) time.Time {

	result := currentTime.Add(self.interval)
	// If we are rolling over at midnight or weekly, then the interval is
	// already known.  What we need to figure out is WHEN the next interval is.
	// In other words, if you are rolling over at midnight, then
	// your base interval is 1 day, but you want to start that one day clock
	// at midnight, not now.
	// So, we have to fudge the rolloverTime value in order trigger the first
	// rollover at the right time.  After that, the regular interval will
	// take care of the rest.
	// Note that this code doesn't care about leap seconds.
	if (self.when == "MIDNIGHT") || strings.HasPrefix(self.when, "W") {
		var t time.Time
		if self.utc {
			t = currentTime.UTC()
		} else {
			t = currentTime.Local()
		}
		dayStartTime := time.Date(
			t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
		result = currentTime.Add(Day - t.Sub(dayStartTime))
		// If we are rolling over on a certain day, add in the number of days
		// until the next rollover, but offset by 1 since we just calculated
		// the time until the next day starts.  There are three cases:
		// Case 1) The day to rollover is today; in this case, do nothing
		// Case 2) The day to rollover is further in the interval (i.e.,
		//         today is day 3 (Wednesday) and rollover is on day 6
		//         (Saturday). Days to next rollover is simply 6 - 3, or 3)
		// Case 3) The day to rollover is behind us in the interval (i.e.,
		//         today is day 5 (Friday) and rollover is on day 4 (Thursday).
		//         Days to rollover is 6 - 5 + 4 + 1, or 6.)  In this case,
		//         it's the number of days left in the current week (1) plus
		//         the number of days in the next week until the
		//         rollover day (5).
		// THe calculations described in 2) and 3) above need to
		// have a day added.  This is because the above time calculation
		// takes us to midnight on this day, i.e., the start of the next day.
		if strings.HasPrefix(self.when, "W") {
			weekday := int(t.Weekday())
			if weekday != self.weekday {
				var daysToWait int
				if weekday < self.weekday {
					daysToWait = self.weekday - weekday
				} else {
					daysToWait = 6 - weekday + self.weekday + 1
				}
				result = result.Add(time.Duration(int64(daysToWait) * int64(Day)))
				// NOTE: we skip the daylight savings time issues here
				// because time library in Golang doesn't support it.
			}
		}
	}
	return result
}
예제 #11
0
파일: time.go 프로젝트: housinganywhere/pg
func AppendTime(b []byte, tm time.Time, quote bool) []byte {
	if quote {
		b = append(b, '\'')
	}
	b = append(b, tm.Local().Format(timestamptzFormat)...)
	if quote {
		b = append(b, '\'')
	}
	return b
}
예제 #12
0
파일: format.go 프로젝트: imoapps/juju
// FormatTime returns a string with the local time formatted
// in an arbitrary format used for status or and localized tz
// or in UTC timezone and format RFC3339 if u is specified.
func FormatTime(t *time.Time, formatISO bool) string {
	if formatISO {
		// If requested, use ISO time format.
		// The format we use is RFC3339 without the "T". From the spec:
		// NOTE: ISO 8601 defines date and time separated by "T".
		// Applications using this syntax may choose, for the sake of
		// readability, to specify a full-date and full-time separated by
		// (say) a space character.
		return t.UTC().Format("2006-01-02 15:04:05Z")
	}
	// Otherwise use local time.
	return t.Local().Format("02 Jan 2006 15:04:05Z07:00")
}
예제 #13
0
파일: tasks.go 프로젝트: devshell/Tasks
//GetTasks retrieves all the tasks depending on the
//status pending or trashed or completed
func GetTasks(status, category string) (types.Context, error) {
	var tasks []types.Task
	var task types.Task
	var TaskCreated time.Time
	var context types.Context
	var getTasksql string
	var rows *sql.Rows

	comments := GetComments()

	basicSQL := "select id, title, content, created_date, priority from task t"
	if status == "pending" && category == "" {
		getTasksql = basicSQL + " where finish_date is null and is_deleted='N' order by priority desc, created_date asc"
	} else if status == "deleted" {
		getTasksql = basicSQL + " where is_deleted='Y' order by priority desc, created_date asc"
	} else if status == "completed" {
		getTasksql = basicSQL + " where finish_date is not null order by priority desc, created_date asc"
	}

	if category != "" {
		status = category
		getTasksql = "select t.id, title, content, created_date, priority from task t, category c where c.id = t.cat_id and name = ?  and  t.is_deleted!='Y' and t.finish_date is null  order by priority desc, created_date asc, finish_date asc"
		rows, err = database.db.Query(getTasksql, category)
		if err != nil {
			log.Println("something went wrong while getting query")
		}
	} else {
		rows = database.query(getTasksql)
	}
	defer rows.Close()
	for rows.Next() {
		task = types.Task{}
		err := rows.Scan(&task.Id, &task.Title, &task.Content, &TaskCreated, &task.Priority)
		task.Content = string(md.Markdown([]byte(task.Content)))
		// TaskContent = strings.Replace(TaskContent, "\n", "<br>", -1)
		if err != nil {
			log.Println(err)
		}

		if comments[task.Id] != nil {
			task.Comments = comments[task.Id]
		}

		TaskCreated = TaskCreated.Local()
		task.Created = TaskCreated.Format(time.UnixDate)[0:20]

		tasks = append(tasks, task)
	}
	context = types.Context{Tasks: tasks, Navigation: status}
	return context, nil
}
예제 #14
0
파일: expr.go 프로젝트: aglagla/kapacitor
func mergeFieldsAndTags(now time.Time, fields models.Fields, tags models.Tags) (*tick.Scope, error) {
	scope := tick.NewScope()
	scope.Set("time", now.Local())
	for k, v := range fields {
		if _, ok := tags[k]; ok {
			return nil, fmt.Errorf("cannot have field and tags with same name %q", k)
		}
		scope.Set(k, v)
	}
	for k, v := range tags {
		scope.Set(k, v)
	}
	return scope, nil
}
예제 #15
0
//SearchTask is used to return the search results depending on the query
func SearchTask(username, query string) (types.Context, error) {
	var tasks []types.Task
	var task types.Task
	var TaskCreated time.Time
	var context types.Context

	comments, err := GetComments(username)
	if err != nil {
		log.Println("SearchTask: something went wrong in finding comments")
	}

	userID, err := GetUserID(username)
	if err != nil {
		return context, err
	}

	stmt := "select t.id, title, content, created_date, priority, c.name from task t, category c where t.user_id=? and c.id = t.cat_id and (title like '%" + query + "%' or content like '%" + query + "%') order by created_date desc"

	rows := database.query(stmt, userID, query, query)
	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&task.Id, &task.Title, &task.Content, &TaskCreated, &task.Priority, &task.Category)
		if err != nil {
			log.Println(err)
		}

		if comments[task.Id] != nil {
			task.Comments = comments[task.Id]
		}

		task.Title = strings.Replace(task.Title, query, "<span class='highlight'>"+query+"</span>", -1)
		task.Content = strings.Replace(task.Content, query, "<span class='highlight'>"+query+"</span>", -1)
		task.Content = string(md.Markdown([]byte(task.Content)))

		TaskCreated = TaskCreated.Local()
		CurrentTime := time.Now().Local()
		week := TaskCreated.AddDate(0, 0, 7)

		if (week.String() < CurrentTime.String()) && (task.Priority != "1") {
			task.IsOverdue = true // If one week then overdue by default
		}
		task.Created = TaskCreated.Format("Jan 2 2006")

		tasks = append(tasks, task)
	}
	context = types.Context{Tasks: tasks, Search: query, Navigation: "search"}
	return context, nil
}
예제 #16
0
func toHumanDateString(date time.Time) string {
	date = date.Local()
	today := time.Now()

	if isSameDate(date, today) {
		return "today"
	} else if isSameDate(date, today.AddDate(0, 0, -1)) {
		return "yesterday"
	} else if isSameWeek(date, today) {
		return date.Weekday().String()
	} else if isDateAfter(date, today.AddDate(0, 0, -7)) {
		return "last " + date.Weekday().String()
	} else {
		return toIsoDateString(date)
	}
}
예제 #17
0
파일: models.go 프로젝트: BitSchupser/gogs
// Note: get back time.Time from database Go sees it at UTC where they are really Local.
// 	So this function makes correct timezone offset.
func regulateTimeZone(t time.Time) time.Time {
	if setting.UseSQLite3 {
		return t
	}

	zone := t.Local().Format("-0700")
	if len(zone) != 5 {
		return t
	}
	offset := com.StrTo(zone[2:3]).MustInt()

	if zone[0] == '-' {
		return t.Add(time.Duration(offset) * time.Hour)
	}
	return t.Add(-1 * time.Duration(offset) * time.Hour)
}
예제 #18
0
파일: models.go 프로젝트: Keleir/gogs
// Note: get back time.Time from database Go sees it at UTC where they are really Local.
// 	So this function makes correct timezone offset.
func regulateTimeZone(t time.Time) time.Time {
	if setting.UseSQLite3 {
		return t
	}

	zone := t.Local().Format("-0700")
	if len(zone) != 5 {
		return t
	}
	hour := com.StrTo(zone[2:3]).MustInt()
	minutes := com.StrTo(zone[3:4]).MustInt()

	if zone[0] == '-' {
		return t.Add(time.Duration(hour) * time.Hour).Add(time.Duration(minutes) * time.Minute)
	}
	return t.Add(-1 * time.Duration(hour) * time.Hour).Add(-1 * time.Duration(minutes) * time.Minute)
}
예제 #19
0
파일: timer.go 프로젝트: jmptrader/letsgo
// return yyyymmdd 格式
func LGToday(times ...interface{}) int {
	var tt time.Time
	if len(times) == 0 {
		tt = time.Now()
	} else {
		ttime := times[0]
		if t, ok := ttime.(time.Time); ok {
			tt = t
		} else if t, ok := ttime.(int); ok {
			tt = time.Unix(int64(t), 0)
		} else if t, ok := ttime.(int64); ok {
			tt = time.Unix(t, 0)
		}
	}

	tt = tt.Local()
	return tt.Year()*10000 + int(tt.Month())*100 + tt.Day()
}
예제 #20
0
// Note: get back time.Time from database Go sees it at UTC where they are really Local.
// 	So this function makes correct timezone offset.
func regulateTimeZone(t time.Time) time.Time {
	/*if !setting.UseMySQL {
		return t
	}*/

	zone := t.Local().Format("-0700")
	if len(zone) != 5 {
		log.Error(4, "Unprocessable timezone: %s - %s", t.Local(), zone)
		return t
	}
	hour := com.StrTo(zone[2:3]).MustInt()
	minutes := com.StrTo(zone[3:5]).MustInt()

	if zone[0] == '-' {
		return t.Add(time.Duration(hour) * time.Hour).Add(time.Duration(minutes) * time.Minute)
	}
	return t.Add(-1 * time.Duration(hour) * time.Hour).Add(-1 * time.Duration(minutes) * time.Minute)
}
예제 #21
0
func runDigest(c *cobra.Command, args []string) error {
	if len(ctx.Repos) == 0 {
		return util.Errorf("repositor(ies) not specified; use --repos=:owner/:repo[,:owner/:repo,...]")
	}
	if len(ctx.Template) == 0 {
		return util.Errorf("template not specified; use --template=:html_template")
	}

	// Parse the "fetch since" date and recast it as a local timezone.
	var err error
	if ctx.FetchSince, err = time.Parse(time.RFC3339, ctx.Since); err != nil {
		return util.Errorf("failed to parse --since=%s: %s", ctx.Since, err)
	}
	ctx.FetchSince = ctx.FetchSince.Local()

	log.Infof("fetching GitHub data for repositor(ies) %s", ctx.Repos)
	open, closed, err := Query(&ctx)
	if err != nil {
		return util.Errorf("failed to query data: %s", err)
	}
	log.Infof("creating digest for repositor(ies) %s", ctx.Repos)
	if err := Digest(&ctx, open, closed); err != nil {
		return util.Errorf("failed to create digest: %s", err)
	}
	var latestTime time.Time
	for _, pr := range open {
		if t := mustParseTime3339(pr.CreatedAt); t.After(latestTime) {
			latestTime = t
		}
	}
	for _, pr := range closed {
		if t := mustParseTime3339(pr.ClosedAt); t.After(latestTime) {
			latestTime = t
		}
	}
	if len(open)+len(closed) == 0 {
		latestTime = time.Now()
	}
	latestTime = latestTime.Local()
	fmt.Fprintf(os.Stdout, "since: %s\n", ctx.FetchSince.Format(time.RFC3339))
	fmt.Fprintf(os.Stdout, "prettysince: %s\n", ctx.FetchSince.Format(time.UnixDate))
	fmt.Fprintf(os.Stdout, "nextsince: %s\n", latestTime.Format(time.RFC3339))
	return nil
}
예제 #22
0
파일: models.go 프로젝트: nafrente/gogs
// Note: get back time.Time from database Go sees it at UTC where they are really Local.
// 	So this function makes correct timezone offset.
func regulateTimeZone(t time.Time) time.Time {
	if !setting.UseMySQL {
		return t
	}

	zone := t.Local().Format("-0700")
	log.Trace("regulateTimeZone: %s - %s", t.Local(), zone)

	if len(zone) != 5 {
		return t
	}
	hour := com.StrTo(zone[2:3]).MustInt()
	minutes := com.StrTo(zone[3:5]).MustInt()

	if zone[0] == '-' {
		return t.Add(time.Duration(hour) * time.Hour).Add(time.Duration(minutes) * time.Minute)
	}
	return t.Add(-1 * time.Duration(hour) * time.Hour).Add(-1 * time.Duration(minutes) * time.Minute)
}
예제 #23
0
파일: sql.go 프로젝트: viking/go-hourglass
func (db *Sql) findActivities(predicate string, args ...interface{}) ([]*Activity, error) {
	var activities []*Activity = nil
	err := &DatabaseErrors{}

	conn, openErr := sql.Open(db.DriverName, db.DataSourceName)
	if openErr != nil {
		err.Append(openErr)
		return activities, err
	}

	query := `SELECT id, name, project, tags, start, end
    FROM activities ` + predicate
	rows, queryErr := db.query(conn, query, args...)

	if queryErr != nil {
		err.Append(queryErr)
	} else {
		for rows.Next() {
			var id int64
			var name, project, tagList string
			var start, end time.Time

			scanErr := rows.Scan(&id, &name, &project, &tagList, &start, &end)
			if scanErr == nil {
				activity := &Activity{Id: id, Name: name, Project: project, Start: start.Local(), End: end.Local()}
				activity.SetTagList(tagList)
				activities = append(activities, activity)
			} else {
				err.Append(scanErr)
			}
		}
	}

	connErr := conn.Close()
	if connErr != nil {
		err.Append(connErr)
	}

	if err.IsEmpty() {
		return activities, nil
	}
	return activities, err
}
예제 #24
0
// If later hasn't happened yet, make it happen on the day of now; if not, the day after.
func bestTime(now time.Time, later time.Time) time.Time {
	now = now.Local() // use local time to make things make sense
	nowh, nowm, nows := now.Clock()
	laterh, laterm, laters := later.Clock()
	add := false
	if nowh > laterh {
		add = true
	} else if (nowh == laterh) && (nowm > laterm) {
		add = true
	} else if (nowh == laterh) && (nowm == laterm) && (nows >= laters) {
		// >= in the case we're on the exact second; add a day because the alarm should have gone off by now otherwise!
		add = true
	}
	if add {
		now = now.AddDate(0, 0, 1)
	}
	return time.Date(now.Year(), now.Month(), now.Day(),
		laterh, laterm, laters, 0,
		now.Location())
}
예제 #25
0
파일: timer.go 프로젝트: jmptrader/letsgo
func LGYesterday(times ...interface{}) int {
	var tt time.Time
	if len(times) == 0 {
		tt = time.Now()
	} else {
		ttime := times[0]
		if t, ok := ttime.(time.Time); ok {
			tt = t
		} else if t, ok := ttime.(int); ok {
			tt = time.Unix(int64(t), 0)
		} else if t, ok := ttime.(int64); ok {
			tt = time.Unix(t, 0)
		}
	}

	tt = tt.AddDate(0, 0, -1)
	tt = tt.Local()
	mm := int(tt.Month())
	return tt.Year()*10000 + mm*100 + tt.Day()

}
예제 #26
0
파일: batch.go 프로젝트: yuanwr/kapacitor
func (b *BatchNode) Queries(start, stop time.Time) []string {
	now := time.Now()
	if stop.IsZero() {
		stop = now
	}
	// Crons are sensitive to timezones.
	// Make sure we are using local time.
	start = start.Local()
	queries := make([]string, 0)
	for {
		start = b.ticker.Next(start)
		if start.IsZero() || start.After(stop) {
			break
		}
		b.query.Start(start)
		qstop := start.Add(b.b.Period)
		if qstop.After(now) {
			break
		}
		b.query.Stop(qstop)
		queries = append(queries, b.query.String())
	}
	return queries
}
예제 #27
0
func logHandler(w http.ResponseWriter, r *http.Request) {
	queryString := r.URL.Path
	queries := strings.Split(queryString, "/")

	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	//db, error := sql.Open("mysql", "gdg:gdg@tcp(173.194.105.240:3306)/andnyang?parseTime=true")
	db, error := sql.Open("mysql", "gdg@cloudsql(andnyang:andnyangdb)/andnyang?parseTime=true")
	if error != nil {
		fmt.Fprint(w, "sql open failed!")
		fmt.Fprintf(w, error.Error())
	}

	if len(queries) < 2 {
		return
	}

	channel := queries[1]
	log.Printf("channel: %s", channel)

	if len(channel) == 0 {
		return
	}

	sqlString := fmt.Sprintf("select * from andnyang_log where channel='#%s'", channel)

	log.Printf("len of queries: %d", len(queries))
	if len(queries) != 3 || len(queries[2]) != 8 {
		now := time.Now().Local()
		year := now.Year()
		month := now.Month()
		day := now.Day()
		path := fmt.Sprintf("/%s/%04d%02d%02d", channel, year, month, day)
		http.Redirect(w, r, path, http.StatusFound)
		return
	}

	dateQuery := queries[2]
	sqlString = sqlString + getSuffixQueryWithDateQuery(dateQuery)
	log.Print(sqlString)

	rows, error := db.Query(sqlString)
	if error != nil {
		log.Print("db query failed!")
		fmt.Fprintf(w, error.Error())
		return
	}

	logs := []Log{}

	for rows.Next() {
		var id int
		var date time.Time
		var channel string
		var nick string
		var message string

		error := rows.Scan(&id, &date, &channel, &nick, &message)
		if error != nil {
			fmt.Fprint(w, "scan failed!")
			fmt.Fprintf(w, error.Error())
			return
		}
		localTime := date.Local()
		hour := localTime.Hour()
		min := localTime.Minute()

		log := Log{
			Id:      id,
			Hour:    hour,
			Min:     min,
			Nick:    nick,
			Message: message,
		}
		logs = append(logs, log)
	}

	filename := "andnyang/log.html"
	body, error := ioutil.ReadFile(filename)
	if error != nil {
		log.Print(error)
	}

	t := template.New("hello template")
	t, error = t.Parse(string(body))
	if error != nil {
		log.Print(error)
	}

	channels := []string{
		"gdgand",
		"gdgwomen",
	}
	currentIndex := -1
	for i, v := range channels {
		if v == channel {
			currentIndex = i
			break
		}
	}
	if currentIndex != -1 {
		lastChannelIndex := len(channels) - 1
		channels[currentIndex] = channels[lastChannelIndex]
		channels = channels[0:lastChannelIndex]
	}

	previousDate, previousLink := getOtherDateQueryAndLink(dateQuery, channel, -1)
	nextDate, nextLink := getOtherDateQueryAndLink(dateQuery, channel, 1)
	container := LogContainer{
		Logs:           logs,
		PreviousDate:   previousDate,
		PreviousLink:   previousLink,
		NextDate:       nextDate,
		NextLink:       nextLink,
		CurrentChannel: channel,
		OtherChannels:  channels,
	}
	t.Execute(w, container)
}
예제 #28
0
//GetTasks retrieves all the tasks depending on the
//status pending or trashed or completed
func GetTasks(username, status, category string) (types.Context, error) {
	log.Println("getting tasks for ", status)
	var tasks []types.Task
	var task types.Task
	var TaskCreated time.Time
	var context types.Context
	var getTaskSQL string
	var rows *sql.Rows

	comments, err := GetComments(username)

	if err != nil {
		return context, err
	}

	basicSQL := "select t.id, title, content, created_date, priority, case when c.name is null then 'NA' else c.name end from task t, status s, user u left outer join  category c on c.id=t.cat_id where u.username=? and s.id=t.task_status_id and u.id=t.user_id "
	if category == "" {
		switch status {
		case "pending":
			getTaskSQL = basicSQL + " and s.status='PENDING' and t.hide!=1"
		case "deleted":
			getTaskSQL = basicSQL + " and s.status='DELETED' and t.hide!=1"
		case "completed":
			getTaskSQL = basicSQL + " and s.status='COMPLETE' and t.hide!=1"
		}

		getTaskSQL += " order by t.created_date asc"

		rows = database.query(getTaskSQL, username, username)
	} else {
		status = category
		//This is a special case for showing tasks with null categories, we do a union query
		if category == "UNCATEGORIZED" {
			getTaskSQL = "select t.id, title, content, created_date, priority, 'UNCATEGORIZED' from task t, status s, user u where u.username=? and s.id=t.task_status_id and u.id=t.user_id and t.cat_id=0  and  s.status='PENDING'  order by priority desc, created_date asc, finish_date asc"
			rows, err = database.db.Query(getTaskSQL, username)
		} else {
			getTaskSQL = basicSQL + " and name = ?  and  s.status='PENDING'  order by priority desc, created_date asc, finish_date asc"
			rows, err = database.db.Query(getTaskSQL, username, category)
		}

		if err != nil {
			log.Println("tasks.go: something went wrong while getting query fetch tasks by category")
		}
	}

	defer rows.Close()
	for rows.Next() {
		task = types.Task{}

		err = rows.Scan(&task.Id, &task.Title, &task.Content, &TaskCreated, &task.Priority, &task.Category)

		taskCompleted := 0
		totalTasks := 0

		if strings.HasPrefix(task.Content, "- [") {
			for _, value := range strings.Split(task.Content, "\n") {
				if strings.HasPrefix(value, "- [x]") {
					taskCompleted += 1
				}
				totalTasks += 1
			}
			task.CompletedMsg = strconv.Itoa(taskCompleted) + " complete out of " + strconv.Itoa(totalTasks)
		}

		task.ContentHTML = template.HTML(md.Markdown([]byte(task.Content)))
		// TaskContent = strings.Replace(TaskContent, "\n", "<br>", -1)
		if err != nil {
			log.Println(err)
		}

		if comments[task.Id] != nil {
			task.Comments = comments[task.Id]
		}

		TaskCreated = TaskCreated.Local()
		// if task.Priority != "1" { // if priority is not 1 then calculate, else why bother?
		// CurrentTime := time.Now().Local()
		// diff := CurrentTime.Sub(TaskCreated).Hours()
		// if diff > 168 {
		// 	task.IsOverdue = true // If one week then overdue by default
		// }
		// }
		task.Created = TaskCreated.Format("Jan 2 2006")

		tasks = append(tasks, task)
	}
	context = types.Context{Tasks: tasks, Navigation: status}
	return context, nil
}
예제 #29
0
파일: sqlite3.go 프로젝트: fclairamb/drone
// Move cursor to next.
func (rc *SQLiteRows) Next(dest []driver.Value) error {
	rv := C.sqlite3_step(rc.s.s)
	if rv == C.SQLITE_DONE {
		return io.EOF
	}
	if rv != C.SQLITE_ROW {
		rv = C.sqlite3_reset(rc.s.s)
		if rv != C.SQLITE_OK {
			return rc.s.c.lastError()
		}
		return nil
	}

	if rc.decltype == nil {
		rc.decltype = make([]string, rc.nc)
		for i := 0; i < rc.nc; i++ {
			rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
		}
	}

	for i := range dest {
		switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
		case C.SQLITE_INTEGER:
			val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
			switch rc.decltype[i] {
			case "timestamp", "datetime", "date":
				unixTimestamp := strconv.FormatInt(val, 10)
				if len(unixTimestamp) == 13 {
					duration, err := time.ParseDuration(unixTimestamp + "ms")
					if err != nil {
						return fmt.Errorf("error parsing %s value %d, %s", rc.decltype[i], val, err)
					}
					epoch := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
					dest[i] = epoch.Add(duration)
				} else {
					dest[i] = time.Unix(val, 0).Local()
				}

			case "boolean":
				dest[i] = val > 0
			default:
				dest[i] = val
			}
		case C.SQLITE_FLOAT:
			dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
		case C.SQLITE_BLOB:
			p := C.sqlite3_column_blob(rc.s.s, C.int(i))
			if p == nil {
				dest[i] = nil
				continue
			}
			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
			switch dest[i].(type) {
			case sql.RawBytes:
				dest[i] = (*[1 << 30]byte)(unsafe.Pointer(p))[0:n]
			default:
				slice := make([]byte, n)
				copy(slice[:], (*[1 << 30]byte)(unsafe.Pointer(p))[0:n])
				dest[i] = slice
			}
		case C.SQLITE_NULL:
			dest[i] = nil
		case C.SQLITE_TEXT:
			var err error
			var timeVal time.Time
			s := C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))))

			switch rc.decltype[i] {
			case "timestamp", "datetime", "date":
				for _, format := range SQLiteTimestampFormats {
					if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
						dest[i] = timeVal.Local()
						break
					}
				}
				if err != nil {
					// The column is a time value, so return the zero time on parse failure.
					dest[i] = time.Time{}
				}
			default:
				dest[i] = []byte(s)
			}

		}
	}
	return nil
}
예제 #30
0
파일: time.go 프로젝트: keysonZZZ/kmg
func ToLocal(t time.Time) time.Time {
	return t.Local()
}