예제 #1
1
func ParseTimeInterval(source string) (time.Duration, error) {
	matches := intervalRegex.FindStringSubmatch(strings.ToLower(source))

	if matches == nil {
		return 0, errors.New("Invalid time interval " + source)
	}

	val, err := strconv.Atoi(matches[1])

	if err != nil {
		return 0, err
	}

	switch matches[2] {
	case "s":
		return time.Duration(val) * time.Second, nil

	case "m":
		return time.Duration(val) * time.Second * 60, nil

	case "h":
		return time.Duration(val) * time.Second * 60 * 60, nil

	case "d":
		return time.Duration(val) * time.Second * 60 * 60 * 24, nil

	case "w":
		return time.Duration(val) * time.Second * 60 * 60 * 24 * 7, nil

	default:
		return 0, errors.New("Invalid time interval " + source)
	}
}
예제 #2
1
func (this *MemeOCR) Run(image string) (*OCRResult, error) {
	imageTif := fmt.Sprintf("%s_meme.jpg", image)
	outText := fmt.Sprintf("%s_meme", image)
	preprocessingArgs := []string{image, "-resize", "400%", "-fill", "black", "-fuzz", "10%", "+opaque", "#FFFFFF", imageTif}
	tesseractArgs := []string{"-l", "meme", imageTif, outText}

	err := runProcessorCommand(GetExecPath(), preprocessingArgs)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Meme preprocessing command failed with error = %v", err))
	}
	defer os.Remove(imageTif)

	err = runProcessorCommand("tesseract", tesseractArgs)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Meme tesseract command failed with error = %v", err))
	}
	defer os.Remove(outText + ".txt")

	text, err := ioutil.ReadFile(outText + ".txt")
	if err != nil {
		return nil, err
	}

	result := strings.ToLower(strings.TrimSpace(string(text[:])))

	return newOCRResult(this.name, result), nil
}
예제 #3
0
func (this *OutboundConnectionConfig) UnmarshalJSON(data []byte) error {
	type JsonConnectionConfig struct {
		Protocol      string                   `json:"protocol"`
		SendThrough   *v2net.AddressJson       `json:"sendThrough"`
		StreamSetting *internet.StreamSettings `json:"streamSettings"`
		Settings      json.RawMessage          `json:"settings"`
	}
	jsonConfig := new(JsonConnectionConfig)
	if err := json.Unmarshal(data, jsonConfig); err != nil {
		return errors.New("Point: Failed to parse outbound config: " + err.Error())
	}
	this.Protocol = jsonConfig.Protocol
	this.Settings = jsonConfig.Settings

	if jsonConfig.SendThrough != nil {
		address := jsonConfig.SendThrough.Address
		if address.Family().IsDomain() {
			return errors.New("Point: Unable to send through: " + address.String())
		}
		this.SendThrough = address
	}
	if jsonConfig.StreamSetting != nil {
		this.StreamSettings = jsonConfig.StreamSetting
	}
	return nil
}
예제 #4
0
파일: mbox.go 프로젝트: aerth/cosgo
// Save saves an mbox file from a mbox.Form!
func Save(form *Form) error {
	t := time.Now()
	if form.Email == "@" || form.Email == " " || !strings.ContainsAny(form.Email, "@") || !strings.ContainsAny(form.Email, ".") {
		return errors.New("Blank email address.")
	}
	if ValidationLevel != 1 {
		err := emailx.Validate(form.Email)
		if err != nil {
			if err == emailx.ErrInvalidFormat {
				return errors.New("Email is not valid format.")
			}
			if err == emailx.ErrUnresolvableHost {
				return errors.New("Email is not valid format.")
			}
			return errors.New("Email is not valid format." + err.Error())
		}
	}
	// Normalize email address capitalization
	form.Email = emailx.Normalize(form.Email)
	// mbox files use two different date formats apparently.
	mailtime := t.Format("Mon Jan 2 15:04:05 2006")
	mailtime2 := t.Format("Mon, 2 Jan 2006 15:04:05 -0700")
	Mail.Println("From " + form.Email + " " + mailtime)
	Mail.Println("Return-path: <" + form.Email + ">")
	Mail.Println("Envelope-to: " + Destination)
	Mail.Println("Delivery-date: " + mailtime2)
	Mail.Println("To: " + Destination)
	Mail.Println("Subject: " + form.Subject)
	Mail.Println("From: " + form.Email)
	Mail.Println("Date: " + mailtime2)
	Mail.Println("\n" + form.Message + "\n\n")
	return nil
}
예제 #5
0
func (this *InboundConnectionConfig) UnmarshalJSON(data []byte) error {
	type JsonConfig struct {
		Port          uint16                   `json:"port"`
		Listen        *v2net.AddressJson       `json:"listen"`
		Protocol      string                   `json:"protocol"`
		StreamSetting *internet.StreamSettings `json:"streamSettings"`
		Settings      json.RawMessage          `json:"settings"`
		AllowPassive  bool                     `json:"allowPassive"`
	}

	jsonConfig := new(JsonConfig)
	if err := json.Unmarshal(data, jsonConfig); err != nil {
		return errors.New("Point: Failed to parse inbound config: " + err.Error())
	}
	this.Port = v2net.Port(jsonConfig.Port)
	this.ListenOn = v2net.AnyIP
	if jsonConfig.Listen != nil {
		if jsonConfig.Listen.Address.Family().IsDomain() {
			return errors.New("Point: Unable to listen on domain address: " + jsonConfig.Listen.Address.Domain())
		}
		this.ListenOn = jsonConfig.Listen.Address
	}
	if jsonConfig.StreamSetting != nil {
		this.StreamSettings = jsonConfig.StreamSetting
	}

	this.Protocol = jsonConfig.Protocol
	this.Settings = jsonConfig.Settings
	this.AllowPassiveConnection = jsonConfig.AllowPassive
	return nil
}
예제 #6
0
파일: starexpr.go 프로젝트: raff/eval
func evalStarExpr(ctx *Ctx, starExpr *StarExpr, env *Env) (*reflect.Value, bool, error) {
	// return nil, false, errors.New("Star expressions not done yet")
	var cexpr Expr
	var errs []error
	if cexpr, errs = CheckExpr(ctx, starExpr.X, env); len(errs) != 0 {
		for _, cerr := range errs {
			fmt.Printf("%v\n", cerr)
		}
		return nil, false, errors.New("Something wrong checking * expression")
	}

	xs, _, err := EvalExpr(ctx, cexpr, env)
	if err != nil {
		return nil, false, err
	} else if xs == nil {
		// XXX temporary error until typed evaluation of nil
		return nil, false, errors.New("Cannot dereferece nil type")
	}

	var x reflect.Value
	if x, err = expectSingleValue(ctx, *xs, starExpr.X); err != nil {
		return nil, false, err
	}

	switch x.Type().Kind() {
	case reflect.Interface, reflect.Ptr:
		val := x.Elem()
		return &val, true, nil
	default:
		return nil, true, ErrInvalidIndirect{x.Type()}
	}
}
예제 #7
0
파일: apply.go 프로젝트: rameshvarun/ups
// Apply applies the patch data to the given base.
func Apply(base []byte, patch *common.PatchData, skipCRC bool) ([]byte, error) {
	if uint64(len(base)) != patch.InputFileSize {
		return nil, errors.New("Base file did not have expected size.")
	}
	if !skipCRC && crc32.ChecksumIEEE(base) != patch.InputChecksum {
		return nil, errors.New("Base file did not have expected checksum")
	}

	output := make([]byte, patch.OutputFileSize)
	copy(output, base)

	pointer := 0
	for _, block := range patch.PatchBlocks {
		pointer += int(block.RelativeOffset)

		for _, b := range block.Data {
			if pointer >= len(base) {
				output[pointer] = b
			} else {
				output[pointer] = base[pointer] ^ b
			}
			pointer++
		}

		pointer++
	}

	if !skipCRC && crc32.ChecksumIEEE(output) != patch.OutputChecksum {
		return nil, errors.New("Patch result did not have expected checksum")
	}

	return output, nil
}
예제 #8
0
파일: raft.go 프로젝트: lebauce/skydive
func (c *Config) validate() error {
	if c.ID == None {
		return errors.New("cannot use none as id")
	}

	if c.HeartbeatTick <= 0 {
		return errors.New("heartbeat tick must be greater than 0")
	}

	if c.ElectionTick <= c.HeartbeatTick {
		return errors.New("election tick must be greater than heartbeat tick")
	}

	if c.Storage == nil {
		return errors.New("storage cannot be nil")
	}

	if c.MaxInflightMsgs <= 0 {
		return errors.New("max inflight messages must be greater than 0")
	}

	if c.Logger == nil {
		c.Logger = raftLogger
	}

	return nil
}
예제 #9
0
// ParseConfigTemplate parses a string into a ConfigTemplate struct
func ParseConfigTemplate(s string) (*ConfigTemplate, error) {
	if len(strings.TrimSpace(s)) < 1 {
		return nil, errors.New("cannot specify empty template declaration")
	}

	var source, destination, command string
	parts := configTemplateRe.FindAllString(s, -1)

	switch len(parts) {
	case 1:
		source = parts[0]
	case 2:
		source, destination = parts[0], parts[1]
	case 3:
		source, destination, command = parts[0], parts[1], parts[2]
	default:
		return nil, errors.New("invalid template declaration format")
	}

	return &ConfigTemplate{
		Source:      source,
		Destination: destination,
		Command:     command,
		Perms:       defaultFilePerms,
	}, nil
}
예제 #10
0
func GetMember(email, password string) (Member, error) {
	log.Printf("Get member '%s' ('%s')", email, password)
	db, err := GetDBConnection()
	if err == nil {
		defer db.Close()
		pwd := sha256.Sum256([]byte(password))
		log.Printf("Encrypted password: %s", hex.EncodeToString(pwd[:]))
		row := db.QueryRow(`SELECT id, email, first_name
			FROM Member
			WHERE email = $1 AND password = $2`,
			email,
			hex.EncodeToString(pwd[:]),
		)
		result := Member{}
		err = row.Scan(&result.id, &result.email, &result.firstName)
		log.Printf("Err: %v", err)
		if err == nil {
			return result, nil
		} else {
			return result, errors.New("Unable to find Member with email: " + email)
		}
	} else {
		return Member{}, errors.New("Unable to get database connection")
	}
}
예제 #11
0
파일: user.go 프로젝트: mikeflynn/iwillvote
func (this *User) Load() error {
	db := NewMySQL()

	params := []interface{}{}
	where := ""

	if this.ID > 0 {
		where = "id=?"
		params = append(params, this.ID)
	} else if this.Network != "" && this.UUID != "" {
		where = "network=? AND uuid=?"
		params = append(params, this.Network, this.UUID)
	} else {
		return errors.New("Message missing required fields for load: id or network and uuid")
	}

	result, err := db.Select("SELECT id, network, uuid, name, state, zipcode, created_on, deleted, landing_page, message_window, news, reminders FROM user WHERE "+where+" LIMIT 1", params...)
	if err != nil {
		return err
	}

	for result.Next() {
		err = result.Scan(&this.ID, &this.Network, &this.UUID, &this.Name, &this.State, &this.Zipcode, &this.CreatedOn, &this.Deleted, &this.LandingPage, &this.MessageWindow, &this.News, &this.Reminders)
		if err != nil {
			log.Println(err.Error())
			return err
		}
	}

	if this.CreatedOn == "" || this.Deleted == 1 {
		return errors.New("User not found or deleted.")
	}

	return nil
}
예제 #12
0
파일: auth.go 프로젝트: Jwpe/l2met
// Extract the username and password from the authorization
// line of an HTTP header. This function will handle the
// parsing and decoding of the line.
func ParseRaw(authLine string) (string, string, error) {
	parts := strings.SplitN(authLine, " ", 2)
	if len(parts) != 2 {
		return "", "", errors.New("Authorization header malformed.")
	}

	method := parts[0]
	if method != "Basic" {
		return "", "", errors.New("Authorization must be basic.")
	}

	payload := parts[1]
	decodedPayload, err := base64.StdEncoding.DecodeString(payload)
	if err != nil {
		return "", "", err
	}

	userPass := strings.SplitN(string(decodedPayload), ":", 2)
	switch len(userPass) {
	case 1:
		return userPass[0], "", nil
	case 2:
		return userPass[0], userPass[1], nil
	}

	return "", "", errors.New("Unable to parse username or password.")
}
예제 #13
0
func CreateSession(m Member) (Session, error) {
	result := Session{}
	result.memberId = m.Id()
	sessionId := sha256.Sum256([]byte(m.Email() + time.Now().Format("12:00:00")))
	result.sessionId = hex.EncodeToString(sessionId[:])

	db, err := GetDBConnection()
	if err == nil {
		defer db.Close()
		err := db.QueryRow(`INSERT INTO Session
			(member_id, session_id)
			VALUES ($1, $2)
			RETURNING id`,
			m.Id(),
			result.sessionId,
		).Scan(&result.id)
		log.Print(err)
		if err == nil {
			return result, nil
		} else {
			return Session{}, errors.New("Unable to save session to database")
		}
	} else {
		return Session{}, errors.New("Unable to get database connection")
	}
}
func testAccCheckAWSALBTargetGroupExists(n string, res *elbv2.TargetGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return errors.New("No Target Group ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).elbv2conn

		describe, err := conn.DescribeTargetGroups(&elbv2.DescribeTargetGroupsInput{
			TargetGroupArns: []*string{aws.String(rs.Primary.ID)},
		})

		if err != nil {
			return err
		}

		if len(describe.TargetGroups) != 1 ||
			*describe.TargetGroups[0].TargetGroupArn != rs.Primary.ID {
			return errors.New("Target Group not found")
		}

		*res = *describe.TargetGroups[0]
		return nil
	}
}
예제 #15
0
// Init initializes this KeyStore with a password, a path to a folder
// where the keys are stored and a read only flag.
// Each key is stored in a separated file whose name contains the key's SKI
// and flags to identity the key's type.
// If the KeyStore is initialized with a password, this password
// is used to encrypt and decrypt the files storing the keys.
// The pwd can be nil for non-encrypted KeyStores. If an encrypted
// key-store is initialized without a password, then retrieving keys from the
// KeyStore will fail.
// A KeyStore can be read only to avoid the overwriting of keys.
func (ks *FileBasedKeyStore) Init(pwd []byte, path string, readOnly bool) error {
	// Validate inputs
	// pwd can be nil

	if len(path) == 0 {
		return errors.New("An invalid KeyStore path provided. Path cannot be an empty string.")
	}

	ks.m.Lock()
	defer ks.m.Unlock()

	if ks.isOpen {
		return errors.New("KeyStore already initilized.")
	}

	ks.path = path
	ks.pwd = utils.Clone(pwd)

	err := ks.createKeyStoreIfNotExists()
	if err != nil {
		return err
	}

	err = ks.openKeyStore()
	if err != nil {
		return err
	}

	ks.readOnly = readOnly

	return nil
}
예제 #16
0
func (h *Host) InitHandler(hl blobserver.FindHandlerByTyper) error {
	_, handler, err := hl.FindHandlerByType("root")
	if err != nil || handler == nil {
		return errors.New("importer requires a 'root' handler")
	}
	rh := handler.(*server.RootHandler)
	searchHandler, ok := rh.SearchHandler()
	if !ok {
		return errors.New("importer requires a 'root' handler with 'searchRoot' defined.")
	}
	h.search = searchHandler
	if rh.Storage == nil {
		return errors.New("importer requires a 'root' handler with 'blobRoot' defined.")
	}
	h.target = rh.Storage

	_, handler, _ = hl.FindHandlerByType("jsonsign")
	if sigh, ok := handler.(*signhandler.Handler); ok {
		h.signer = sigh.Signer()
	}
	if h.signer == nil {
		return errors.New("importer requires a 'jsonsign' handler")
	}

	return nil
}
예제 #17
0
func (inode *DirectoryInode) rebuildInodePointers(fs *FileSystem) error {
	for _, dirent := range inode.EntryList {
		tableInode, ok := fs.InodeTable[dirent.InodeNumber]
		if !ok {
			return errors.New(fmt.Sprintf(
				"%s: no entry in inode table for: %d %p",
				dirent.Name, dirent.InodeNumber, dirent.inode))
		}
		if tableInode == nil {
			return errors.New(fmt.Sprintf(
				"%s: nil entry in inode table for: %d %p",
				dirent.Name, dirent.InodeNumber, dirent.inode))
		} else if dirent.inode != nil && dirent.inode != tableInode {
			return errors.New(fmt.Sprintf(
				"%s: changing inode entry for: %d from: %p to %p\n",
				dirent.Name, dirent.InodeNumber, dirent.inode, tableInode))
		}
		dirent.inode = tableInode
		if inode, ok := dirent.inode.(*DirectoryInode); ok {
			if err := inode.rebuildInodePointers(fs); err != nil {
				return errors.New(dirent.Name + "/" + err.Error())
			}
		}
	}
	return nil
}
예제 #18
0
파일: struct.go 프로젝트: swan-go/gopm
func (n *Node) DownloadByGit(ctx *cli.Context, u *url.URL) error {
	var remoteAddr string
	switch u.Scheme {
	case "git+ssh":
		remoteAddr = fmt.Sprintf("git@%s:%s.git", u.Host, u.Path)
	case "git+http":
		remoteAddr = fmt.Sprintf("http://%s/%s", u.Host, u.Path)
	case "git+https":
		remoteAddr = fmt.Sprintf("https://%s/%s", u.Host, u.Path)
	}
	baseDir := path.Dir(n.InstallPath)
	os.MkdirAll(baseDir, os.ModePerm)
	_, stderr, err := base.ExecCmdDir(baseDir, "git", "clone", remoteAddr, n.InstallPath)
	if err != nil {
		log.Error("Error occurs when 'git clone " + remoteAddr + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	if !n.IsEmptyVal() {
		base.ExecCmdDir(n.InstallPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	return nil
}
예제 #19
0
func (mkc *MockKafkaClient) GetBoundingOffsets(topic string, partition int32) (int64,
	int64, error) {
	topicMap, ok := mkc.messages[topic]
	if !ok {
		return -1, -1, errors.New("No such topic")
	}

	partMap, ok := topicMap[partition]
	if !ok {
		return -1, -1, errors.New("No such partition")
	}

	// because apparently Go is too cool to give native sorting for
	// int64, and the tests will never need offsets > 32 bits
	var offsets []int
	for offset, _ := range partMap {
		offsets = append(offsets, int(offset))
	}

	if len(offsets) == 0 {
		return 0, 0, nil
	}

	sort.Ints(offsets)
	return int64(offsets[0]), int64(offsets[len(offsets)-1]) + 1, nil
}
예제 #20
0
파일: issues.go 프로젝트: tokams/autograder
func FindIssuesPointsAndTrophyAction(payload IssuesPayload) (int, int, error) {
	if payload.Action == nil {
		return 0, 0, errors.New("Cant use empty Action on issues payload.")
	}

	var p int
	var ta int
	switch *payload.Action {
	case "assigned":
		p = points.ASSIGNMENT
		ta = trophies.ASSIGNACTION
	case "unassigned":
		p = points.UNASSIGNMENT
		ta = trophies.ASSIGNACTION
	case "labeled":
		p = points.LABEL
		ta = trophies.LABELACTION
	case "unlabeled":
		p = points.UNLABEL
		ta = trophies.LABELACTION
	case "opened":
		p = points.OPEN_ISSUE
		ta = trophies.ISSUEACTION
	case "closed":
		p = points.CLOSE_ISSUE
		ta = trophies.ISSUEACTION
	case "reopened":
		p = points.REOPEN_ISSUE
		ta = trophies.ISSUEACTION
	default:
		return 0, 0, errors.New("Issue action not known for " + *payload.Action)
	}

	return p, ta, nil
}
예제 #21
0
파일: struct.go 프로젝트: swan-go/gopm
// Download downloads remote package without version control.
func (n *Node) Download(ctx *cli.Context) ([]string, error) {
	for _, s := range services {
		if !strings.HasPrefix(n.DownloadURL, s.prefix) {
			continue
		}

		m := s.pattern.FindStringSubmatch(n.DownloadURL)
		if m == nil {
			if s.prefix != "" {
				return nil, errors.New("Cannot match package service prefix by given path")
			}
			continue
		}

		match := map[string]string{"downloadURL": n.DownloadURL}
		for i, n := range s.pattern.SubexpNames() {
			if n != "" {
				match[n] = m[i]
			}
		}
		return s.get(HttpClient, match, n, ctx)

	}

	if n.ImportPath != n.DownloadURL {
		return nil, errors.New("Didn't find any match service")
	}

	log.Info("Cannot match any service, getting dynamic...")
	return n.getDynamic(HttpClient, ctx)
}
예제 #22
0
func (this *StandardOCR) Run(image string) (*OCRResult, error) {
	imageTif := fmt.Sprintf("%s_standard.jpg", image)
	outText := fmt.Sprintf("%s_standard", image)

	preprocessingArgs := []string{image, "-resize", "400%", "-type", "Grayscale", imageTif}
	tesseractArgs := []string{"-l", "eng", imageTif, outText}

	err := runProcessorCommand(GetExecPath(), preprocessingArgs)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Standard preprocessing command failed with error = %v", err))
	}
	defer os.Remove(imageTif)

	err = runProcessorCommand("tesseract", tesseractArgs)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Standard tesseract command failed with error = %v", err))
	}
	defer os.Remove(outText + ".txt")

	text, err := ioutil.ReadFile(outText + ".txt")
	if err != nil {
		return nil, err
	}

	result := strings.ToLower(strings.TrimSpace(string(text[:])))

	return newOCRResult(this.name, result), nil
}
예제 #23
0
파일: struct.go 프로젝트: swan-go/gopm
func (n *Node) DownloadByGoGet(ctx *cli.Context, u *url.URL) error {
	baseDir := path.Join(setting.HomeDir, ".gopm/temp/goget")
	os.MkdirAll(baseDir, os.ModePerm)
	defer func() {
		os.RemoveAll(baseDir)
	}()

	oriGopath := os.Getenv("GOPATH")
	os.Setenv("GOPATH", baseDir)
	fmt.Println(baseDir)
	defer func() {
		os.Setenv("GOPATH", oriGopath)
	}()

	log.Debug("RUN 'go get %s'", n.RootPath)
	_, stderr, err := base.ExecCmdDir(baseDir, "go", "get", n.RootPath)
	if err != nil {
		log.Error("Error occurs when 'go get" + n.RootPath + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	tmpPath := path.Join(baseDir, "src", n.RootPath)
	if !n.IsEmptyVal() {
		base.ExecCmdDir(tmpPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	os.MkdirAll(path.Dir(n.InstallPath), os.ModePerm)
	os.Rename(tmpPath, n.InstallPath)
	return nil
}
예제 #24
0
func (p *textPlistParser) parseGNUStepValue(v []byte) *plistValue {
	if len(v) < 2 {
		panic(errors.New("invalid GNUStep extended value"))
	}
	typ := v[1]
	v = v[2:]
	switch typ {
	case 'I':
		if v[0] == '-' {
			n := mustParseInt(string(v), 10, 64)
			return &plistValue{Integer, signedInt{uint64(n), true}}
		} else {
			n := mustParseUint(string(v), 10, 64)
			return &plistValue{Integer, signedInt{n, false}}
		}
	case 'R':
		n := mustParseFloat(string(v), 64)
		return &plistValue{Real, sizedFloat{n, 64}}
	case 'B':
		b := v[0] == 'Y'
		return &plistValue{Boolean, b}
	case 'D':
		t, err := time.Parse(textPlistTimeLayout, string(v))
		if err != nil {
			panic(err)
		}

		return &plistValue{Date, t.In(time.UTC)}
	}
	panic(errors.New("invalid GNUStep type " + string(typ)))
	return nil
}
예제 #25
0
func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}
예제 #26
0
// List returns the identities known to the agent.
func (c *client) List() ([]*Key, error) {
	// see [PROTOCOL.agent] section 2.5.2.
	req := []byte{agentRequestIdentities}

	msg, err := c.call(req)
	if err != nil {
		return nil, err
	}

	switch msg := msg.(type) {
	case *identitiesAnswerAgentMsg:
		if msg.NumKeys > maxAgentResponseBytes/8 {
			return nil, errors.New("agent: too many keys in agent reply")
		}
		keys := make([]*Key, msg.NumKeys)
		data := msg.Keys
		for i := uint32(0); i < msg.NumKeys; i++ {
			var key *Key
			var err error
			if key, data, err = parseKey(data); err != nil {
				return nil, err
			}
			keys[i] = key
		}
		return keys, nil
	case *failureAgentMsg:
		return nil, errors.New("agent: failed to list keys")
	}
	panic("unreachable")
}
예제 #27
0
// Read is like (*os.File).Read()
// Visit http://golang.org/pkg/os/#File.Read for more information
func (f *File) Read(bts []byte) (int, error) {
	if f.appendedF != nil {
		if f.appendedFileReader == nil {
			return 0, &os.PathError{
				Op:   "read",
				Path: filepath.Base(f.appendedF.zipFile.Name),
				Err:  errors.New("file is closed"),
			}
		}
		if f.appendedF.dir {
			return 0, &os.PathError{
				Op:   "read",
				Path: filepath.Base(f.appendedF.zipFile.Name),
				Err:  errors.New("is a directory"),
			}
		}
		return f.appendedFileReader.Read(bts)
	}
	if f.virtualF != nil {
		return f.virtualF.read(bts)
	}
	if f.virtualD != nil {
		return f.virtualD.read(bts)
	}
	return f.realF.Read(bts)
}
예제 #28
0
func (this *ParentHandler) SendOut() error {
	for {
		//		packet := <-this.sendQueue
		//从sendQueue中接收数据
		packet := this.SendQueuePop()

		if packet == nil {
			err := errors.New("component: ParentHandler.SendOut() failed, got a nil pointer form ParentHandler.sendQueue")
			fmt.Println(err.Error())
			continue
		}
		buf, err := packet.Encode()
		if err != nil {
			err = errors.New("component: ParentHandler.SendOut failed, can not got the buf from packet")
			fmt.Println(err.Error())
			continue
		}
		if this.masterConn == nil {
			fmt.Println("\n", time.Now().String(), " STree's parent(Root)'s conn is invalid", "\n")
			time.Sleep(30 * time.Second)
			continue
		}
		//向10.0.0.11:11002中写入Packet的buf
		_, err = (*this.masterConn).Write(buf)
		if err != nil {
			err = errors.New("component: ParentHandler.SendOut failed, can not send packet to parent's master connection, will switch to slave connection")
			fmt.Println(err.Error())
			continue
		}
	}
}
예제 #29
0
파일: start.go 프로젝트: gmelika/rack
func dockerTest() error {
	dockerTest := exec.Command("docker", "images")
	err := dockerTest.Run()
	if err != nil {
		return errors.New("could not connect to docker daemon, is it installed and running?")
	}

	dockerVersionTest, err := docker.NewClientFromEnv()
	if err != nil {
		return err
	}

	minDockerVersion, err := docker.NewAPIVersion("1.9")
	e, err := dockerVersionTest.Version()
	if err != nil {
		return err
	}

	currentVersionParts := strings.Split(e.Get("Version"), ".")
	currentVersion, err := docker.NewAPIVersion(fmt.Sprintf("%s.%s", currentVersionParts[0], currentVersionParts[1]))
	if err != nil {
		return err
	}

	if !(currentVersion.GreaterThanOrEqualTo(minDockerVersion)) {
		return errors.New("Your version of docker is out of date (min: 1.9)")
	}
	return nil
}
예제 #30
0
파일: base.go 프로젝트: cronosun/buranv1
func (self *base) createBucketId(typeId bucket.TypeId) (
	bucketId bucket.Id, err error) {
	if typeId.IsMetadata() {
		err = errors.New("It's not possible to create a bucket ID for metadata")
		return
	}

	// Lock database
	self.createBucketIdMutex.Lock()
	defer self.createBucketIdMutex.Unlock()
	db := self.createDatabase
	for index := 0; index < bucketIdGenTries; index++ {
		var candidate bucket.Id
		candidate, err = createBucketIdCandidate(typeId)
		if err != nil {
			// Genrating a condidate should never fail
			return
		}
		_, err = db.Get(candidate, nil)
		if err == leveldb.ErrNotFound {
			// Great, found a non-empty entry
			err = db.Put(candidate, []byte{byte(typeId)}, nil)
			if err == nil {
				// Could store it, it's now created
				return candidate, nil
			}
		}
		log.Printf("Bucket ID %v already found", candidate)
	}
	return nil, errors.New("Could not find a new bucket id")
}