Example #1
1
func (w *Worker) ExecBin(binPath string, args []string, maxRunTime int64) (string, error) {
	var cmd *exec.Cmd
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	var err error

	if len(args) == 0 {
		cmd = exec.Command(binPath)
	} else {
		cmd = exec.Command(binPath, args...)
	}

	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	cmd.Start() // attention!

	err, _ = w.CmdRunWithTimeout(cmd,
		time.Duration(maxRunTime)*time.Second,
	)
	if err != nil {
		return "", err
	}
	if len(stderr.String()) != 0 {
		errMsg := strings.TrimRight(stderr.String(), "\n")
		return "", errors.NewError(errMsg)
	}

	return strings.TrimRight(stdout.String(), "\n"), nil
}
Example #2
0
func (p *Post) Fill(url string) {
	doc, err := goquery.NewDocument(url)
	if err != nil {
		log.Fatal(err)
	}

	//   doc.Find(".blog-post").Each(func(i int, s *goquery.Selection) {
	//     band := s.Find("h3").Text()
	//     title := s.Find("i").Text()
	//     fmt.Printf("Review %d: %s - %s\n", i, band, title)
	//   })

	title := doc.Find(".blog-post").Find(".blog-post-title").Text()
	date := doc.Find(".blog-post").Find(".blog-post-meta").Text()
	text, _ := doc.Find(".blog-post").Find("span").Html()
	slug := strings.TrimLeft(url, "http://speedyspin.ru/")

	p.Body = text
	p.Shortmessage = text
	p.Slug = slug
	p.Status = 1
	p.Title = title

	p.Created, _ = fmtdate.Parse("DD.MM.YYYY", strings.TrimRight(date, " автор Виталий"))
	p.Modified, _ = fmtdate.Parse("DD.MM.YYYY", strings.TrimRight(date, " автор Виталий"))
}
Example #3
0
func (p partedPartitioner) GetDeviceSizeInBytes(devicePath string) (uint64, error) {
	p.logger.Debug(p.logTag, "Getting size of disk remaining after first partition")

	stdout, _, _, err := p.cmdRunner.RunCommand("parted", "-m", devicePath, "unit", "B", "print")
	if err != nil {
		return 0, bosherr.WrapErrorf(err, "Getting remaining size of `%s'", devicePath)
	}

	allLines := strings.Split(stdout, "\n")
	if len(allLines) < 3 {
		return 0, bosherr.Errorf("Getting remaining size of `%s'", devicePath)
	}

	partitionInfoLines := allLines[1:3]
	deviceInfo := strings.Split(partitionInfoLines[0], ":")
	deviceFullSizeInBytes, err := strconv.ParseUint(strings.TrimRight(deviceInfo[1], "B"), 10, 64)
	if err != nil {
		return 0, bosherr.WrapErrorf(err, "Getting remaining size of `%s'", devicePath)
	}

	firstPartitionInfo := strings.Split(partitionInfoLines[1], ":")
	firstPartitionEndInBytes, err := strconv.ParseUint(strings.TrimRight(firstPartitionInfo[2], "B"), 10, 64)
	if err != nil {
		return 0, bosherr.WrapErrorf(err, "Getting remaining size of `%s'", devicePath)
	}

	remainingSizeInBytes := deviceFullSizeInBytes - firstPartitionEndInBytes - 1

	return remainingSizeInBytes, nil
}
Example #4
0
func decodeTime(r io.Reader, f reflect.Value) error {
	s, err := decodeStr(r)
	if err != nil {
		return err
	}
	var t time.Time
	if s != "" {
		// Samsung has trailing dots.
		s = strings.TrimRight(s, ".")

		// Jolla Sailfish has trailing "Z".
		s = strings.TrimRight(s, "Z")

		t, err = time.Parse(timeFormat, s)
		if err != nil {
			// Nokia lumia has numTZ
			t, err = time.Parse(timeFormatNumTZ, s)
			if err != nil {
				return err
			}
		}
	}
	f.Set(reflect.ValueOf(t))
	return nil
}
Example #5
0
// processString is utilized by DecodeHDU to process string-type values in the header
// it uses a 3-state machine to process double single quotes
func processString(s string) (string, int, error) {
	var buf bytes.Buffer

	state := 0
	for i, char := range s {
		quote := (char == '\'')
		switch state {
		case 0:
			if !quote {
				return "", i, fmt.Errorf("fitsio: string does not start with a quote (%q)", s)
			}
			state = 1
		case 1:
			if quote {
				state = 2
			} else {
				buf.WriteRune(char)
				state = 1
			}
		case 2:
			if quote {
				buf.WriteRune(char)
				state = 1
			} else {
				return strings.TrimRight(buf.String(), " "), i, nil
			}
		}
	}
	if s[len(s)-1] == '\'' {
		return strings.TrimRight(buf.String(), " "), len(s), nil
	}
	return "", 0, fmt.Errorf("fitsio: string ends prematurely (%q)", s)
}
Example #6
0
func (d *Decimal) String() (s string) {
	if len(d.a) == 0 {
		return "0"
	}
	if d.neg {
		s = "-"
	}
	value := d.a.string10()
	multiplier := len(d.b.string10())
	if multiplier == 1 {
		return s + value
	}
	valsize := len(value)
	diff := multiplier - valsize
	if diff > 0 {
		s += "0"
		rhs := ""
		for i := 0; i < diff-1; i++ {
			rhs += "0"
		}
		rhs = strings.TrimRight(rhs+value, "0")
		if len(rhs) > 0 {
			return s + "." + rhs
		}
		return "0"
	}
	diff = valsize - multiplier + 1
	rhs := strings.TrimRight(value[diff:], "0")
	if len(rhs) > 0 {
		return s + value[:diff] + "." + rhs
	}
	return s + value[:diff]
}
Example #7
0
func (s *RunCommandSuite) TestRunCommandsEnvStdOutAndErrAndRC(c *gc.C) {
	// TODO(bogdanteleaga): powershell throws another exit status code when
	// outputting to stderr using Write-Error. Either find another way to
	// output to stderr or change the checks
	if runtime.GOOS == "windows" {
		c.Skip("bug 1403084: Have to figure out a good way to output to stderr from powershell")
	}
	ctx, err := s.contextFactory.HookContext(hook.Info{Kind: hooks.ConfigChanged})
	c.Assert(err, jc.ErrorIsNil)
	paths := runnertesting.NewRealPaths(c)
	runner := runner.NewRunner(ctx, paths)

	commands := `
echo $JUJU_CHARM_DIR
echo this is standard err >&2
exit 42
`
	result, err := runner.RunCommands(commands)
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(result.Code, gc.Equals, 42)
	c.Assert(strings.TrimRight(string(result.Stdout), "\r\n"), gc.Equals, paths.GetCharmDir())
	c.Assert(strings.TrimRight(string(result.Stderr), "\r\n"), gc.Equals, "this is standard err")
	c.Assert(ctx.GetProcess(), gc.NotNil)
}
Example #8
0
func createRegularModeData(index int, offset int, infoType DockerInfoType, cont *goDocker.Container) (info string) {

	switch infoType {
	case ImageInfo:
		info = cont.Config.Image
	case Names:
		info = cont.Name
		if cont.Node != nil {
			info = cont.Node.Name + info
		}
	case PortInfo:
		info = createPortsString(cont.NetworkSettings.Ports, ",")
	case BindInfo:
		info = strings.TrimRight(strings.Join(cont.HostConfig.Binds, ","), ",")
	case CommandInfo:
		info = cont.Path + " " + strings.Join(cont.Args, " ")
	case EnvInfo:
		info = strings.TrimRight(strings.Join(cont.Config.Env, ","), ",")
	case EntrypointInfo:
		info = strings.Join(cont.Config.Entrypoint, " ")
	case VolumesInfo:
		volStr := ""
		for intVol, hostVol := range cont.Volumes {
			volStr += intVol + ":" + hostVol + ","
		}
		info = strings.TrimRight(volStr, ",")
	case TimeInfo:
		info = cont.State.StartedAt.Format(time.RubyDate)
	default:
		Error.Println("Unhandled info type", infoType)
	}
	return
}
Example #9
0
// get repository keys from s3
func (remote *S3Remote) repoKeys(prefix string) (keys, error) {
	repoKeys := make(keys)

	prefix = strings.TrimLeft(strings.TrimRight(prefix, "/"), "/")
	keyPrefix := strings.TrimRight(remote.KeyPrefix, "/")

	bucketPrefix := keyPrefix + "/" + prefix
	remotePrefix := keyPrefix + "/"

	bucket := remote.getBucket()

	cnt, err := bucket.GetBucketContentsWithPrefix(bucketPrefix)
	if err != nil {
		return repoKeys, fmt.Errorf("getting bucket contents at prefix '%s': %s", prefix, err)
	}

	for _, key := range *cnt {
		if key.Key == "" {
			continue
		}

		plainKey := strings.TrimPrefix(key.Key, remotePrefix)

		if strings.HasSuffix(plainKey, ".sum") {
			plainKey = strings.TrimSuffix(plainKey, ".sum")
			repoKeys.Get(plainKey, remote).sumKey = key.Key

		} else {
			repoKeys.Get(plainKey, remote).s3Key = key
		}
	}

	return repoKeys, nil
}
Example #10
0
File: pack.go Project: 2thetop/go
// readMetadata reads and parses the metadata for the next entry in the archive.
func (ar *Archive) readMetadata() *Entry {
	buf := make([]byte, entryLen)
	_, err := io.ReadFull(ar.fd, buf)
	if err == io.EOF {
		// No entries left.
		return nil
	}
	if err != nil || buf[entryLen-2] != '`' || buf[entryLen-1] != '\n' {
		log.Fatal("file is not an archive: bad entry")
	}
	entry := new(Entry)
	entry.name = strings.TrimRight(string(buf[:16]), " ")
	if len(entry.name) == 0 {
		log.Fatal("file is not an archive: bad name")
	}
	buf = buf[16:]
	str := string(buf)
	get := func(width, base, bitsize int) int64 {
		v, err := strconv.ParseInt(strings.TrimRight(str[:width], " "), base, bitsize)
		if err != nil {
			log.Fatal("file is not an archive: bad number in entry: ", err)
		}
		str = str[width:]
		return v
	}
	// %-16s%-12d%-6d%-6d%-8o%-10d`
	entry.mtime = get(12, 10, 64)
	entry.uid = int(get(6, 10, 32))
	entry.gid = int(get(6, 10, 32))
	entry.mode = os.FileMode(get(8, 8, 32))
	entry.size = get(10, 10, 64)
	return entry
}
Example #11
0
//生成插入的SQL语句,和对应的参数
func generateInsertSql(model interface{}) (string, []interface{}, *TableInfo, error) {
	tbinfo, err := getTableInfo(model)
	if err != nil {
		return "", nil, nil, err
	}

	//如果结构体中没有字段,抛出异常
	if len(tbinfo.Fields) == 0 {
		return "", nil, nil, errors.New(tbinfo.Name + "结构体中没有字段")
	}
	strSql := "insert into " + tbinfo.Name
	strField := ""
	strValue := ""
	var param []interface{}
	for _, v := range tbinfo.Fields {
		if v.IsAutoGenerate { //跳过自动增长的自段
			continue
		}
		strField += v.Name + ","
		strValue += "?,"
		param = append(param, v.Value.Interface())
	}
	if strField == "" {
		return "", nil, nil, errors.New(tbinfo.Name + "结构体中没有字段,或只有自增自段")
	}
	strField = strings.TrimRight(strField, ",")
	strValue = strings.TrimRight(strValue, ",")
	strSql += " (" + strField + ") values(" + strValue + ")"
	return strSql, param, tbinfo, nil
}
Example #12
0
File: value.go Project: askk/ripple
// String returns the Value as a string for human consumption. Native values are
// represented as decimal XRP rather than drips.
func (v Value) String() string {
	if v.IsZero() {
		return "0"
	}
	if !v.IsNative() && v.isScientific() {
		value := strconv.FormatUint(v.num, 10)
		origLen := len(value)
		value = strings.TrimRight(value, "0")
		offset := strconv.FormatInt(v.offset+int64(origLen-len(value)), 10)
		if v.negative {
			return "-" + value + "e" + offset
		}
		return value + "e" + offset
	}
	rat := v.Rat()
	if v.IsNative() {
		rat.Quo(rat, big.NewRat(int64(xrpPrecision), 1))
	}
	left := rat.FloatString(0)
	if rat.IsInt() {
		return left
	}
	length := len(left)
	if v.negative {
		length -= 1
	}
	return strings.TrimRight(rat.FloatString(32-length), "0")
}
Example #13
0
func inWatch(event_path, fn string) bool {
	event_fn := event_path
	if strings.HasPrefix(event_path, "SUCCESS:") {
		event_fn = event_path[9:]
	} else if strings.HasPrefix(event_path, "FAIL:") {
		event_fn = event_path[6:]
	}
	if strings.HasSuffix(event_fn, "/") {
		event_fn = strings.TrimRight(event_fn, "/")
	}
	if strings.HasSuffix(fn, "/") {
		fn = strings.TrimRight(fn, "/")
	}
	if event_fn == fn {
		return true
	}
	dir, _ := filepath.Split(event_fn)
	if strings.HasSuffix(dir, "/") {
		dir = strings.TrimRight(dir, "/")
	}
	if fn == dir {
		return true
	}
	return false
}
Example #14
0
func (p *CPrinter) PrintFor(init, cond, post string) {
	init = strings.TrimRight(init, SEMI)
	post = strings.TrimRight(post, SEMI)

	onlycond := len(init) == 0 && len(post) == 0

	if len(cond) == 0 {
		cond = "true"
	}

	if onlycond {
		// make it a while
		p.PrintLevel(NONE, "while (", cond)
	} else {
		p.PrintLevel(NONE, "for (")
		if len(init) > 0 {
			p.Print(init)
		}
		p.Print("; " + cond + ";")
		if len(post) > 0 {
			p.Print(" " + post)
		}

	}
	p.Print(") ")
}
Example #15
0
func getGoCompilerVersion() (uint, error) {
	if goCompilerVersion == nil {
		args := []string{goCompiler_exe.name, "-V"}
		stdout, _, err := goCompiler_exe.run(args /*dir*/, "" /*in*/, "" /*mergeStdoutAndStderr*/, true)
		if err != nil {
			return 0, errors.New("failed to determine Go compiler version: " + err.Error())
		}

		stdout = strings.TrimSpace(stdout)
		var stdout_split []string = strings.Split(stdout, " ")
		if len(stdout_split) < 3 {
			return 0, errors.New("failed to extract [Go compiler version] from string \"" + stdout + "\"" +
				" (possible cause: you didn't have the Mercurial versioning system installed when you were compiling the Go distribution)")
		}

		version, err := strconv.ParseUint(strings.TrimRight(stdout_split[2], "+"), 10, 0)
		if (err != nil) && (len(stdout_split) >= 4) {
			version, err = strconv.ParseUint(strings.TrimRight(stdout_split[3], "+"), 10, 0)
		}
		if err != nil {
			return 0, errors.New("failed to extract [Go compiler version] from string \"" + stdout + "\"")
		}

		goCompilerVersion = new(uint)
		*goCompilerVersion = uint(version)
	}

	return *goCompilerVersion, nil
}
Example #16
0
// treeCommandFunc executes the "tree" command.
func treeCommandFunc(c *cli.Context) {
	if len(c.Args()) == 0 {
		fatal("You need to specify directory")
	}
	dir := c.Args()[0]

	// Remove trailing slash.
	if dir != "/" {
		dir = strings.TrimRight(dir, "/")
	}
	infof("Using dir: %s", dir)

	// Load configuration file.
	e := loadConfig(c)

	// New dir API.
	ki := newKeyAPI(e)

	sort := c.Bool("sort")

	resp, err := ki.Get(context.TODO(), dir, &client.GetOptions{Sort: sort, Recursive: true})
	if err != nil {
		fatal(err.Error())
	}

	numDirs = 0
	numKeys = 0
	fmt.Println(strings.TrimRight(dir, "/") + "/")
	printTree(resp.Node, "")
	fmt.Printf("\n%d directories, %d dirs\n", numDirs, numKeys)
}
Example #17
0
// ParsePreferHeader parses the LDP specific Prefer header
func ParsePreferHeader(header string) *Preferheaders {
	ret := new(Preferheaders)

	for _, v := range strings.Split(header, ",") {
		item := new(preferheader)
		v = strings.TrimSpace(v)
		if strings.HasPrefix(v, "return=representation") {
			for _, s := range strings.Split(v, ";") {
				s = strings.TrimSpace(s)
				if strings.HasPrefix(s, "omit") {
					s = strings.TrimLeft(s, "omit=")
					s = strings.TrimLeft(s, "\"")
					s = strings.TrimRight(s, "\"")
					for _, u := range strings.Split(s, " ") {
						item.omit = append(item.omit, u)
					}
				}
				if strings.HasPrefix(s, "include") {
					s = strings.TrimLeft(s, "include=")
					s = strings.TrimLeft(s, "\"")
					s = strings.TrimRight(s, "\"")
					for _, u := range strings.Split(s, " ") {
						item.include = append(item.include, u)
					}
				}
			}
			ret.headers = append(ret.headers, item)
		}
	}

	return ret
}
Example #18
0
// View get view data to template from Context
func (ctx *Context) View() map[string]interface{} {
	m := map[string]interface{}{
		"Version":   vars.Version,
		"Source":    ctx.Source,
		"Nav":       ctx.Source.Nav,
		"Meta":      ctx.Source.Meta,
		"Title":     ctx.Source.Meta.Title + " - " + ctx.Source.Meta.Subtitle,
		"Desc":      ctx.Source.Meta.Desc,
		"Comment":   ctx.Source.Comment,
		"Owner":     ctx.Source.Owner,
		"Analytics": ctx.Source.Analytics,
		"Tree":      ctx.Tree,
		"Lang":      ctx.Source.Meta.Language,
		"Hover":     "",
		"Base":      strings.TrimRight(ctx.Source.Meta.Path, "/"),
		"Root":      strings.TrimRight(ctx.Source.Meta.Root, "/"),
	}
	if ctx.Source.Meta.Language == "" {
		m["I18n"] = ctx.Source.I18n["en"]
		if m["I18n"] == nil {
			m["I18n"] = helper.NewI18nEmpty()
		}
	} else {
		if i18n, ok := ctx.Source.I18n[ctx.Source.Meta.Language]; ok {
			m["I18n"] = i18n
		} else {
			m["I18n"] = helper.NewI18nEmpty()
		}
	}
	return m
}
Example #19
0
func main() {
	r := bufio.NewReader(os.Stdin)
	s, _ := r.ReadString('\n')
	s = strings.TrimRight(s, "\n\r")
	s = strings.TrimRight(s, "\n")
	password(s)
}
Example #20
0
func GetDobjInfoForJoin(object interface{}) (key, fileds, rel_fileds string) {
	object_type := reflect.TypeOf(object).Elem()
	num_filed := object_type.NumField()
	if num_filed > 0 {
		key = strings.ToLower(object_type.Field(0).Name)
	} else {
		return
	}

	table_name := GetDobjTableName(object)
	for i := 0; i < num_filed; i++ {
		object_filed := object_type.Field(i)
		filed_name := strings.ToLower(object_filed.Name)

		field_tag := object_filed.Tag
		if string(field_tag) != "" {
			if field_tag.Get("skip") == "true" {
				continue
			}

			if field_tag.Get("primary_key") == "true" {
				key = filed_name
			}
		}

		fileds += "`" + filed_name + "`, "
		rel_fileds += table_name + "." + filed_name + " as `" + filed_name + "`, "
	}

	key = "`" + key + "`"
	fileds = strings.TrimRight(fileds, ", ")
	rel_fileds = strings.TrimRight(rel_fileds, ", ")

	return
}
Example #21
0
func (d *Decimal) Components() (*Int, *Int) {
	if len(d.a) == 0 {
		return NewIntComponent("0", false), nil
	}
	value := d.a.string10()
	multiplier := len(d.b.string10())
	if multiplier == 1 {
		return NewIntComponent(value, d.neg), nil
	}
	valsize := len(value)
	diff := multiplier - valsize
	if diff > 0 {
		rhs := ""
		for i := 0; i < diff-1; i++ {
			rhs += "0"
		}
		rhs = strings.TrimRight(rhs+value, "0")
		if len(rhs) > 0 {
			return NewIntComponent("0", d.neg), NewIntComponent(pad40("1"+rhs), false)
		}
		return NewIntComponent("0", false), nil
	}
	diff = valsize - multiplier + 1
	rhs := strings.TrimRight(value[diff:], "0")
	if len(rhs) > 0 {
		return NewIntComponent(value[:diff], d.neg), NewIntComponent(pad40("1"+rhs), false)
	}
	return NewIntComponent(value[:diff], false), nil
}
Example #22
0
func readOptionFromFile() {
	f, err := os.Open(opt.formatFile)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	buf := bufio.NewReader(f)
	const fmtCnt = 2
	line := [fmtCnt]string{}
	for i := 0; i < fmtCnt; i++ {
		line[i], err = buf.ReadString('\n')
		if err == io.EOF {
			break
		} else if err != nil {
			panic(fmt.Sprintf("Error reading from format file %v", err))
		}
	}
	if opt.binaryFmt == "" {
		opt.binaryFmt = strings.TrimRight(line[0], "\n")
	}
	if opt.printFmt == "" {
		opt.printFmt = strings.TrimRight(line[1], "\n")
	}
}
Example #23
0
func getFilePath(dir, pattern string) (found string, err error) {
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return
	}

	for _, file := range files {
		fileName := file.Name()
		path := fileName

		if ext := filepath.Ext(fileName); ext == ".md" {
			path = strings.TrimRight(fileName, ".md")
		} else if ext == ".txt" {
			path = strings.TrimRight(fileName, ".txt")
		}

		path = strings.ToLower(path)

		if ok, _ := filepath.Match(pattern, path); ok {
			found = filepath.Join(dir, fileName)
			return
		}
	}
	return
}
Example #24
0
func main() {
	regexName, _ := regexp.Compile(`[a-z]+`)
	regexEmail, _ := regexp.Compile(`[a-z]+@gmail\.[a-z]+`)

	//read in from stdin
	reader := bufio.NewReader(os.Stdin)

	//read in number of input lines
	stringRaw, _ := reader.ReadString('\n')
	string := strings.TrimRight(stringRaw, "\r\n")
	numberLines, _ := strconv.Atoi(string)

	var list = LinkedList{}

	//read in input and check for validity
	for i := 0; i < numberLines; i++ {
		stringRaw, _ := reader.ReadString('\n')
		string := strings.TrimRight(stringRaw, "\r\n")
		var args = strings.Split(string, " ")

		var nameMatch = regexName.FindString(args[0])
		var emailMatch = regexEmail.FindString(args[1])

		if len(nameMatch) > 0 && len(nameMatch) <= 20 && len(emailMatch) > 0 && len(emailMatch) <= 50 {
			list.insert(nameMatch)
		}
	}

	list.display()
}
Example #25
0
// GetTokenInfo obtains information about a particular token
// in the system.
func (c *Ctx) GetTokenInfo(slotID uint) (TokenInfo, error) {
	var cti C.CK_TOKEN_INFO
	e := C.GetTokenInfo(c.ctx, C.CK_ULONG(slotID), &cti)
	s := TokenInfo{
		Label:              strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.label[0]), 32)), " "),
		ManufacturerID:     strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.manufacturerID[0]), 32)), " "),
		Model:              strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.model[0]), 16)), " "),
		SerialNumber:       strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.serialNumber[0]), 16)), " "),
		Flags:              uint(cti.flags),
		MaxSessionCount:    uint(cti.ulMaxSessionCount),
		SessionCount:       uint(cti.ulSessionCount),
		MaxRwSessionCount:  uint(cti.ulMaxRwSessionCount),
		RwSessionCount:     uint(cti.ulRwSessionCount),
		MaxPinLen:          uint(cti.ulMaxPinLen),
		MinPinLen:          uint(cti.ulMinPinLen),
		TotalPublicMemory:  uint(cti.ulTotalPublicMemory),
		FreePublicMemory:   uint(cti.ulFreePublicMemory),
		TotalPrivateMemory: uint(cti.ulTotalPrivateMemory),
		FreePrivateMemory:  uint(cti.ulFreePrivateMemory),
		HardwareVersion:    toVersion(cti.hardwareVersion),
		FirmwareVersion:    toVersion(cti.firmwareVersion),
		UTCTime:            strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.utcTime[0]), 16)), " "),
	}
	return s, toError(e)
}
Example #26
0
func (i *RequestInput) extractFilterItem(keys []string, value []string) (err error) {
	if len(keys) != 2 {
		return errors.New("filter[filters] must have two sub-parameters")
	}
	var idx int
	if idx, err = strconv.Atoi(strings.TrimRight(keys[0], "]")); err != nil {
		return
	}
	if l := len(i.Filter.Filters); l <= idx {
		i.Filter.Filters = append(i.Filter.Filters, make([]FilterItem, idx-l+1)...)
	}
	switch strings.TrimRight(keys[1], "]") {
	case "field":
		i.Filter.Filters[idx].Field, err = getString(value)
	case "ignoreCase":
		i.Filter.Filters[idx].IgnoreCase, err = getBool(value)
	case "operator":
		i.Filter.Filters[idx].Operator, err = getString(value)
	case "value":
		i.Filter.Filters[idx].Value, err = getString(value)
	default:
		err = errors.New("filter[filters][<index>] has unsupported sub-parameter")
	}
	return
}
Example #27
0
func (p partedPartitioner) getPartitions(devicePath string) (partitions []existingPartition, deviceFullSizeInBytes uint64, err error) {
	stdout, _, _, err := p.runPartedPrint(devicePath)

	if err != nil {
		return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Running parted print")
	}

	allLines := strings.Split(stdout, "\n")
	if len(allLines) < 2 {
		return partitions, deviceFullSizeInBytes, bosherr.Errorf("Parsing existing partitions")
	}

	deviceInfo := strings.Split(allLines[1], ":")
	deviceFullSizeInBytes, err = strconv.ParseUint(strings.TrimRight(deviceInfo[1], "B"), 10, 64)
	if err != nil {
		return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing device size")
	}

	partitionLines := allLines[2 : len(allLines)-1]

	for _, partitionLine := range partitionLines {
		// ignore PReP partition on ppc64le
		if strings.Contains(partitionLine, "prep") {
			continue
		}
		partitionInfo := strings.Split(partitionLine, ":")
		partitionIndex, err := strconv.Atoi(partitionInfo[0])

		if err != nil {
			return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
		}

		partitionStartInBytes, err := strconv.Atoi(strings.TrimRight(partitionInfo[1], "B"))
		if err != nil {
			return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
		}

		partitionEndInBytes, err := strconv.Atoi(strings.TrimRight(partitionInfo[2], "B"))
		if err != nil {
			return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
		}

		partitionSizeInBytes, err := strconv.Atoi(strings.TrimRight(partitionInfo[3], "B"))
		if err != nil {
			return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
		}

		partitions = append(
			partitions,
			existingPartition{
				Index:        partitionIndex,
				SizeInBytes:  uint64(partitionSizeInBytes),
				StartInBytes: uint64(partitionStartInBytes),
				EndInBytes:   uint64(partitionEndInBytes),
			},
		)
	}

	return partitions, deviceFullSizeInBytes, nil
}
Example #28
0
func Graylog2ParseLog(line string, remote_addr string) Graylog2Parsed {
	parsed := Graylog2Parsed{}
	now := time.Now()
	parsed.Timestamp = now.Unix()
	parsed.Version = "1.0"
	if strings.Contains(remote_addr, "127.0.0.1") {
		hostname, err := os.Hostname()
		utils.CheckPanic(err, fmt.Sprintf("Unable to get my hostname"))
		parsed.Host = hostname
	} else {
		parsed.Host = remote_addr
	}

	lvl := LvlRegex.FindStringSubmatch(line)
	if len(lvl) >= 2 {
		i, err := strconv.Atoi(lvl[1])
		utils.Check(err, fmt.Sprintf("Unable to convert %s to int", i))
		parsed.Facility = strings.Title(Facility[i/8])
		parsed.Level = i % 8
		parsed.ShortMessage = strings.TrimRight(lvl[2], "\u0000")
	} else {
		parsed.Facility = "Syslog"
		parsed.Level = 6
		parsed.ShortMessage = strings.TrimRight(line, "\u0000")
	}
	return parsed
}
Example #29
0
// Lexes a string in single quotes, whitespaces in the string are permitted.
// Example: 'foo bar is great'
func lexQuotedString(l *lexer) stateFn {
	// the string only consists of the current fild
	if strings.HasPrefix(l.input[l.start], "'") && strings.HasSuffix(l.input[l.start], "'") {
		out := strings.TrimPrefix(l.input[l.start], "'")
		out = strings.TrimRight(out, "'")
		l.emit(STRING, out)
		return lexAttributes
	}

	// the string consists of multiple fields
	out := make([]string, 0)
	out = append(out, strings.TrimPrefix(l.input[l.start], "'"))
	l.pos++
	for {
		if l.pos == len(l.input) {
			l.eof("QuotedString")
		}

		if strings.HasSuffix(l.input[l.pos], "'") {
			out = append(out, strings.TrimRight(l.input[l.pos], "'"))
			l.emit(STRING, strings.Join(out, " "))
			return lexAttributes
		}

		out = append(out, l.input[l.pos])

		l.pos++
	}
}
Example #30
0
func (m postgresqlDriver) generateSQLFromFields(fields string) string {
	sql, tags := "", ""
	fds := strings.Split(fields, ",")
	for i, v := range fds {
		kv := strings.SplitN(v, ":", 2)
		if len(kv) != 2 {
			ColorLog("[ERRO] Fields format is wrong. Should be: key:type,key:type " + v + "\n")
			return ""
		}
		typ, tag := m.getSQLType(kv[1])
		if typ == "" {
			ColorLog("[ERRO] Fields format is wrong. Should be: key:type,key:type " + v + "\n")
			return ""
		}
		if i == 0 && strings.ToLower(kv[0]) != "id" {
			sql += "id serial primary key,"
		}
		sql += snakeString(kv[0]) + " " + typ + ","
		if tag != "" {
			tags = tags + fmt.Sprintf(tag, snakeString(kv[0])) + ","
		}
	}
	if tags != "" {
		sql = strings.TrimRight(sql+" "+tags, ",")
	} else {
		sql = strings.TrimRight(sql, ",")
	}
	return sql
}