Esempio n. 1
0
// ParseDate attempts to parse a string into a local date. Leading
// and trailing space and quotation marks are ignored. The following
// date formates are recognised: yyyy-mm-dd, yyyymmdd, yyyy.mm.dd,
// yyyy/mm/dd, yyyy-ddd, yyyyddd.
func ParseDate(s string) (LocalDate, error) {
	s = strings.Trim(s, " \t\"'")
	for _, regexp := range calendarDateFormats {
		match := regexp.FindStringSubmatch(s)
		if match != nil {
			// no error checking here because matching the regexp
			// guarantees that parsing the strings will succeed.
			year, _ := strconv.ParseInt(match[1], 10, 0)
			month, _ := strconv.ParseInt(match[2], 10, 0)
			day, _ := strconv.ParseInt(match[3], 10, 0)
			return Date(int(year), time.Month(month), int(day)), nil
		}
	}

	for _, regexp := range ordinalDateFormats {
		match := regexp.FindStringSubmatch(s)
		if match != nil {
			// no error checking here because matching the regexp
			// guarantees that parsing the strings will succeed.
			year, _ := strconv.ParseInt(match[1], 10, 0)
			dayOfYear, _ := strconv.ParseInt(match[2], 10, 0)
			duration := time.Duration((dayOfYear - 1) * nanosecondsPerDay)
			return Date(int(year), 1, 1).Add(duration), nil
		}
	}

	return LocalDate{}, errInvalidDateFormat
}
Esempio n. 2
0
File: parse.go Progetto: spkg/local
// DateTimeParse attempts to parse a string into a local date-time. Leading
// and trailing space and quotation marks are ignored. The following
// date formates are recognized: yyyy-mm-dd, yyyymmdd, yyyy.mm.dd,
// yyyy/mm/dd, yyyy-ddd, yyyyddd. The following time formats are recognized:
// HH:MM:SS, HH:MM, HHMMSS, HHMM.
func DateTimeParse(s string) (DateTime, error) {
	s = strings.Trim(s, " \t\"'")
	for _, regexp := range parseRegexp.calendarDateTimes {
		match := regexp.FindStringSubmatch(s)
		if match != nil {
			// no error checking here because matching the regexp
			// guarantees that parsing the strings will succeed.
			year, _ := strconv.ParseInt(match[1], 10, 0)
			month, _ := strconv.ParseInt(match[2], 10, 0)
			day, _ := strconv.ParseInt(match[3], 10, 0)

			var hour, minute, second int64
			if len(match) > 4 {
				hour, _ = strconv.ParseInt(match[4], 10, 0)
			}
			if len(match) > 5 {
				minute, _ = strconv.ParseInt(match[5], 10, 0)
			}
			if len(match) > 6 {
				second, _ = strconv.ParseInt(match[6], 10, 0)
			}

			return DateTimeFor(int(year), time.Month(month), int(day), int(hour), int(minute), int(second)), nil
		}
	}

	for _, regexp := range parseRegexp.ordinalDateTimes {
		match := regexp.FindStringSubmatch(s)
		if match != nil {
			// no error checking here because matching the regexp
			// guarantees that parsing the strings will succeed.
			year, _ := strconv.ParseInt(match[1], 10, 0)
			dayOfYear, _ := strconv.ParseInt(match[2], 10, 0)

			var hour, minute, second int64
			if len(match) > 3 {
				hour, _ = strconv.ParseInt(match[3], 10, 0)
			}
			if len(match) > 4 {
				minute, _ = strconv.ParseInt(match[4], 10, 0)
			}
			if len(match) > 5 {
				second, _ = strconv.ParseInt(match[5], 10, 0)
			}

			duration := time.Duration((dayOfYear - 1) * nanosecondsPerDay)
			return DateTimeFor(int(year), 1, 1, int(hour), int(minute), int(second)).Add(duration), nil
		}
	}

	return DateTime{}, errInvalidDateTimeFormat
}
Esempio n. 3
0
// RegexMatch returns if a string matches a regexp.
func RegexMatch(input string, exp string) string {
	regexp := regexp.MustCompile(exp)
	matches := regexp.FindStringSubmatch(input)
	if len(matches) != 2 {
		return StringEmpty
	}
	return strings.TrimSpace(matches[1])
}
Esempio n. 4
0
func (self *Controller) Handle(c http.ResponseWriter, req *http.Request) {
	fmt.Printf("Handling %v\n", req)

	for d := self.callbacks.Front(); d != nil; d = d.Next() {
		callback := d.Value.(*callback)

		match := `^` + callback.match

		regexp, ok := regexp.Compile(match)
		if ok != nil {
			fmt.Printf("Match could not compile: %#v\n", match)
			continue
		}

		values := make([]string, 0)
		if callback.funcType.NumIn() > 0 {
			values = regexp.FindStringSubmatch(req.URL.Path)
		}

		fmt.Printf("Match: %s, %s, %v\n", match, req.URL.Path, values)

		fmt.Printf(
			"Value count: %v, required args: %v\n",
			len(values)-1+2, callback.funcType.NumIn())

		if len(values) == 0 || (len(values)-1+2) != callback.funcType.NumIn() {
			fmt.Printf("Skipping!\n")
			continue
		}

		args := make([]reflect.Value, len(values)-1+2)

		args[0] = reflect.ValueOf(c)
		args[1] = reflect.ValueOf(req)
		for i := 0; i < len(values)-1; i++ {
			switch callback.funcType.In(i + 2).Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				asInt, ok := strconv.Atoi(values[i+1])
				if ok == nil {
					args[i+2] = reflect.ValueOf(asInt)
				} else {
					args[i+2] = reflect.ValueOf(-1)
				}
			case reflect.Bool:
				args[i+2] = reflect.ValueOf(values[i+1] == "1" || values[i+1] == "true")
			default:
				args[i+2] = reflect.ValueOf(values[i+1])
			}
		}

		fmt.Printf("Invoking callback with %v\n", args)

		callback.funcValue.Call(args)

		return
	}
}
Esempio n. 5
0
func writeToConsole(readChan chan string, writeChan chan string, wg *sync.WaitGroup, quit chan bool, quitChans chan chan bool) {
	defer wg.Done()
	defer fmt.Println("WTC") //debug

	pingRegex := regexp.MustCompile("^PING (.*)")
	questionRegex := regexp.MustCompile(`^:(\S*?)!(\S*?)@(\S*?) PRIVMSG (\S*) :` + config.Nick + `.*\?`)
	ctcpRegex := regexp.MustCompile(`^:(\S*?)!(\S*?)@(\S*?) PRIVMSG (\S*) :` + "\x01" + `(.*?)` + "\x01" + `$`)
	inviteRegex := regexp.MustCompile(`^:(\S*)?!(\S*)?@(\S*)? INVITE (` + config.Nick + `) :\s*(.*)`)

	//read every line from the server chan and print to console
	for {
		lastPing := time.Now().Add((-6) * time.Minute) //time of last PING (initialize to 6 minutes ago)
		betweenPings := time.Now().Sub(lastPing)       //time between last two PINGs
		pingTimer := time.After(betweenPings * 2)

		select {
		case <-quit: //exit if indicated
			return
		case line := <-readChan:
			log.Println(line)
			if match := pingRegex.FindStringSubmatch(line); match != nil {
				betweenPings = time.Now().Sub(lastPing)
				lastPing = time.Now()
				pingTimer = time.After(betweenPings * 2)

				//respond to PING from server
				writeChan <- ("PONG " + match[1])
				log.Println("PONG", match[1])
			} else if match := questionRegex.FindStringSubmatch(line); match != nil {
				go yesNo(writeChan, match[4], match[1], match[3]) //reply Yes or No if bot was asked a question
			} else if match := ctcpRegex.FindStringSubmatch(line); match != nil {
				go ctcp(writeChan, match[4], match[1], match[3], strings.Fields(match[5])) //reply with CTCP if CTCP request was received
			} else if match := inviteRegex.FindStringSubmatch(line); match != nil {
				writeChan <- "JOIN " + match[5]
			} else {
				var match []string
				for _, regexp := range regexpCmds {
					if match = regexp.FindStringSubmatch(line); match != nil {
						cmdArgs := strings.Fields(match[5]) //first word is command, the rest (if any) are args for the command
						if cmd, valid := funcMap[strings.ToLower(cmdArgs[0])]; valid {
							if match[4] == config.Nick {
								match[4] = match[1]
							}
							go cmd(writeChan, match[4], match[1], match[3], cmdArgs[1:])
						}
						break
					}
				}
			}
			break
		case <-pingTimer:
			errOut(errors.New("Server read timeout"), quitChans)
		}
	}
}
Esempio n. 6
0
// Given a command generated by one of the Execute methods in main.go, extracts the value of the
// run_id command-line flag. If not found, signals a test failure.
func getRunId(t *testing.T, cmd *exec.Command) string {
	regexp := regexp.MustCompile("^--run_id=(.*)$")
	for _, arg := range cmd.Args {
		match := regexp.FindStringSubmatch(arg)
		if match != nil && len(match) >= 2 {
			return match[1]
		}
	}
	assert.Contains(t, strings.Join(cmd.Args, " "), "--run_id=")
	assert.Nil(t, "getRunId is broken")
	return ""
}
Esempio n. 7
0
// Generate generate metrics values
func (g *MemoryGenerator) Generate() (metrics.Values, error) {
	file, err := os.Open("/proc/meminfo")
	if err != nil {
		memoryLogger.Errorf("Failed (skip these metrics): %s", err)
		return nil, err
	}
	scanner := bufio.NewScanner(file)

	ret := make(map[string]float64)
	used := float64(0)
	usedCnt := 0
	for scanner.Scan() {
		line := scanner.Text()
		for k, regexp := range memItems {
			if matches := regexp.FindStringSubmatch(line); matches != nil {
				// ex.) MemTotal:        3916792 kB
				// matches[1] = 3916792, matches[2] = kB
				if matches[2] != "kB" {
					memoryLogger.Warningf("/proc/meminfo contains an invalid unit: %s", k)
					break
				}
				value, err := strconv.ParseFloat(matches[1], 64)
				if err != nil {
					memoryLogger.Warningf("Failed to parse memory metrics: %s", err)
					break
				}
				ret["memory."+k] = value * 1024
				if k == "free" || k == "buffers" || k == "cached" {
					used -= value
					usedCnt++
				}
				if k == "total" {
					used += value
					usedCnt++
				}
				break
			}
		}
	}
	if err := scanner.Err(); err != nil {
		memoryLogger.Errorf("Failed (skip these metrics): %s", err)
		return nil, err
	}
	if usedCnt == 4 { // 4 is free, buffers, cached and total
		ret["memory.used"] = used * 1024
	}

	return metrics.Values(ret), nil
}