예제 #1
0
// Valid returns true if every validation passes.
func (cv *ChartValidation) Valid() bool {
	var valid bool = true

	fmt.Printf("\nVerifying %s chart is a valid chart...\n", cv.ChartName())
	cv.walk(func(v *Validation) bool {
		v.path = cv.Path
		vv := v.valid()
		if !vv {
			switch v.level {
			case 2:
				cv.ErrorCount = cv.ErrorCount + 1
				msg := v.Message + " : " + strconv.FormatBool(vv)
				log.Err(msg)
			case 1:
				cv.WarningCount = cv.WarningCount + 1
				msg := v.Message + " : " + strconv.FormatBool(vv)
				log.Warn(msg)
			}
		} else {
			msg := v.Message + " : " + strconv.FormatBool(vv)
			log.Info(msg)
		}

		valid = valid && vv
		return valid
	})

	return valid
}
예제 #2
0
파일: volume.go 프로젝트: blablacar/dgr
func (v Volume) String() string {
	s := []string{
		v.Name.String(),
		",kind=",
		v.Kind,
	}
	if v.Source != "" {
		s = append(s, ",source=")
		s = append(s, v.Source)
	}
	if v.ReadOnly != nil {
		s = append(s, ",readOnly=")
		s = append(s, strconv.FormatBool(*v.ReadOnly))
	}
	if v.Recursive != nil {
		s = append(s, ",recursive=")
		s = append(s, strconv.FormatBool(*v.Recursive))
	}
	switch v.Kind {
	case "empty":
		if *v.Mode != emptyVolumeDefaultMode {
			s = append(s, ",mode=")
			s = append(s, *v.Mode)
		}
		if *v.UID != emptyVolumeDefaultUID {
			s = append(s, ",uid=")
			s = append(s, strconv.Itoa(*v.UID))
		}
		if *v.GID != emptyVolumeDefaultGID {
			s = append(s, ",gid=")
			s = append(s, strconv.Itoa(*v.GID))
		}
	}
	return strings.Join(s, "")
}
예제 #3
0
func clientStats(c ClientStats, acc telegraf.Accumulator, host, version, topic, channel string) {
	tags := map[string]string{
		"server_host":       host,
		"server_version":    version,
		"topic":             topic,
		"channel":           channel,
		"client_name":       c.Name,
		"client_id":         c.ID,
		"client_hostname":   c.Hostname,
		"client_version":    c.Version,
		"client_address":    c.RemoteAddress,
		"client_user_agent": c.UserAgent,
		"client_tls":        strconv.FormatBool(c.TLS),
		"client_snappy":     strconv.FormatBool(c.Snappy),
		"client_deflate":    strconv.FormatBool(c.Deflate),
	}

	fields := map[string]interface{}{
		"ready_count":    c.ReadyCount,
		"inflight_count": c.InFlightCount,
		"message_count":  c.MessageCount,
		"finish_count":   c.FinishCount,
		"requeue_count":  c.RequeueCount,
	}
	acc.AddFields("nsq_client", fields, tags)
}
예제 #4
0
/*
 List sprints

 rapidViewId 	int		Id of board
 history 		bool 	List completed sprints
 future			bool	List sprints in the future

*/
func (j *Jira) ListSprints(rapidViewId int, history bool, future bool) (*Sprints, error) {

	url := j.BaseUrl + j.GreenHopper + sprintQuery_url + "/" + strconv.Itoa(rapidViewId) + "?"

	url += "includeHistoricSprints=" + strconv.FormatBool(history)
	url += "&includeFutureSprints=" + strconv.FormatBool(future)

	if j.Debug {
		fmt.Println(url)
	}

	contents := j.buildAndExecRequest("GET", url, nil)

	sprints := new(Sprints)
	err := json.Unmarshal(contents, &sprints)
	if err != nil {
		fmt.Println("%s", err)
	}

	if j.Debug {
		fmt.Println(sprints)
	}

	return sprints, err
}
예제 #5
0
파일: server.go 프로젝트: jmcarbo/smtpd-1
// Initialize websocket from incus
func setupWebSocket(cfg config.WebConfig, ds *data.DataStore) {
	mymap := make(map[string]string)

	mymap["client_broadcasts"] = strconv.FormatBool(cfg.ClientBroadcasts)
	mymap["connection_timeout"] = strconv.Itoa(cfg.ConnTimeout)
	mymap["redis_enabled"] = strconv.FormatBool(cfg.RedisEnabled)
	mymap["debug"] = "true"

	conf := incus.InitConfig(mymap)
	store := incus.InitStore(&conf)
	Websocket = incus.CreateServer(&conf, store)

	log.LogInfo("Incus Websocket Init")

	go func() {
		for {
			select {
			case msg := <-ds.NotifyMailChan:
				go Websocket.AppListener(msg)
			}
		}
	}()

	go Websocket.RedisListener()
	go Websocket.SendHeartbeats()
}
예제 #6
0
파일: cmd.go 프로젝트: Endika/tsuru
func (c *autoScaleInfoCmd) render(context *cmd.Context, config *autoScaleConfig, rules []autoScaleRule) error {
	fmt.Fprintf(context.Stdout, "Metadata filter: %s\n\n", config.GroupByMetadata)
	var table cmd.Table
	tableHeader := []string{
		"Filter value",
		"Max container count",
		"Max memory ratio",
		"Scale down ratio",
		"Rebalance on scale",
		"Enabled",
	}
	table.Headers = tableHeader
	for _, rule := range rules {
		table.AddRow([]string{
			rule.MetadataFilter,
			strconv.Itoa(rule.MaxContainerCount),
			strconv.FormatFloat(float64(rule.MaxMemoryRatio), 'f', 4, 32),
			strconv.FormatFloat(float64(rule.ScaleDownRatio), 'f', 4, 32),
			strconv.FormatBool(!rule.PreventRebalance),
			strconv.FormatBool(rule.Enabled),
		})
	}
	fmt.Fprintf(context.Stdout, "Rules:\n%s", table.String())
	return nil
}
예제 #7
0
func (c Client) New(params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error) {
	body := &stripe.RequestValues{}
	body.Add("customer", params.Customer)
	body.Add("amount", strconv.FormatInt(params.Amount, 10))
	body.Add("currency", string(params.Currency))

	if len(params.Invoice) > 0 {
		body.Add("invoice", params.Invoice)
	}

	if len(params.Desc) > 0 {
		body.Add("description", params.Desc)
	}

	if len(params.Sub) > 0 {
		body.Add("subscription", params.Sub)
	}

	if params.Discountable {
		body.Add("discountable", strconv.FormatBool(true))
	} else if params.NoDiscountable {
		body.Add("discountable", strconv.FormatBool(false))
	}

	params.AppendTo(body)

	invoiceItem := &stripe.InvoiceItem{}
	err := c.B.Call("POST", "/invoiceitems", c.Key, body, &params.Params, invoiceItem)

	return invoiceItem, err
}
예제 #8
0
파일: context.go 프로젝트: zaolab/sunnified
func makeRequestData(k string, c map[string]interface{}, f url.Values) {
	if k != "" {
		k = k + "."
	}

	for _k, _v := range c {
		key := k + _k
		switch _s := _v.(type) {
		case []interface{}:
			for i, v := range _s {
				switch s := v.(type) {
				case string:
					f.Add(key, s)
				case json.Number:
					f.Add(key, s.String())
				case bool:
					f.Add(key, strconv.FormatBool(s))
				case map[string]interface{}:
					if key != "" {
						key = fmt.Sprintln("%s.%d", key, i)
					}
					makeRequestData(key, s, f)
				}
			}
		case string:
			f.Add(key, _s)
		case json.Number:
			f.Add(key, _s.String())
		case bool:
			f.Add(key, strconv.FormatBool(_s))
		case map[string]interface{}:
			makeRequestData(key, _s, f)
		}
	}
}
예제 #9
0
// Build builds the camlistore command at the given path from the source tree root.
func build(path string) error {
	if v, _ := strconv.ParseBool(os.Getenv("CAMLI_FAST_DEV")); v {
		// Demo mode. See dev/demo.sh.
		return nil
	}
	_, cmdName := filepath.Split(path)
	target := filepath.Join("camlistore.org", path)
	binPath := filepath.Join("bin", cmdName)
	var modtime int64
	fi, err := os.Stat(binPath)
	if err != nil {
		if !os.IsNotExist(err) {
			return fmt.Errorf("Could not stat %v: %v", binPath, err)
		}
	} else {
		modtime = fi.ModTime().Unix()
	}
	args := []string{
		"run", "make.go",
		"--quiet",
		"--race=" + strconv.FormatBool(*race),
		"--embed_static=false",
		"--sqlite=" + strconv.FormatBool(withSqlite),
		fmt.Sprintf("--if_mods_since=%d", modtime),
		"--targets=" + target,
	}
	cmd := exec.Command("go", args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("Error building %v: %v", target, err)
	}
	return nil
}
예제 #10
0
func (client *DockerClient) ContainerLogs(id string, options *LogOptions) (io.ReadCloser, error) {
	v := url.Values{}
	v.Add("follow", strconv.FormatBool(options.Follow))
	v.Add("stdout", strconv.FormatBool(options.Stdout))
	v.Add("stderr", strconv.FormatBool(options.Stderr))
	v.Add("timestamps", strconv.FormatBool(options.Timestamps))
	if options.Tail > 0 {
		v.Add("tail", strconv.FormatInt(options.Tail, 10))
	}
	if options.Since > 0 {
		v.Add("since", strconv.Itoa(options.Since))
	}

	uri := fmt.Sprintf("/%s/containers/%s/logs?%s", APIVersion, id, v.Encode())
	req, err := http.NewRequest("GET", client.URL.String()+uri, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	resp, err := client.HTTPClient.Do(req)
	if err != nil {
		return nil, err
	}
	return resp.Body, nil
}
예제 #11
0
파일: context.go 프로젝트: chrisp-fb/rell
// Serialize the context back to URL values.
func (c *Env) Values() url.Values {
	values := url.Values{}
	if c.appID != c.defaultAppID {
		values.Set("appid", strconv.FormatUint(c.appID, 10))
	}
	if c.Env != defaultContext.Env {
		values.Set("server", c.Env)
	}
	if c.locale != defaultContext.locale {
		values.Set("locale", c.locale)
	}
	if c.Module != defaultContext.Module {
		values.Set("module", c.Module)
	}
	if c.Init != defaultContext.Init {
		values.Set("init", strconv.FormatBool(c.Init))
	}
	if c.Status != defaultContext.Status {
		values.Set("status", strconv.FormatBool(c.Status))
	}
	if c.FrictionlessRequests != defaultContext.FrictionlessRequests {
		values.Set("frictionlessRequests", strconv.FormatBool(c.FrictionlessRequests))
	}
	return values
}
예제 #12
0
파일: aci-build.go 프로젝트: blablacar/dgr
func (aci *Aci) prepareRktRunArguments(command common.BuilderCommand, builderHash string, stage1Hash string) []string {
	var args []string

	if logs.IsDebugEnabled() {
		args = append(args, "--debug")
	}
	args = append(args, "--set-env="+common.EnvDgrVersion+"="+BuildVersion)
	args = append(args, "--set-env="+common.EnvLogLevel+"="+logs.GetLevel().String())
	args = append(args, "--set-env="+common.EnvAciPath+"="+aci.path)
	args = append(args, "--set-env="+common.EnvAciTarget+"="+aci.target)
	args = append(args, "--set-env="+common.EnvBuilderCommand+"="+string(command))
	args = append(args, "--set-env="+common.EnvCatchOnError+"="+strconv.FormatBool(aci.args.CatchOnError))
	args = append(args, "--set-env="+common.EnvCatchOnStep+"="+strconv.FormatBool(aci.args.CatchOnStep))
	args = append(args, "--net=host")
	args = append(args, "--insecure-options=image")
	args = append(args, "--uuid-file-save="+aci.target+pathBuilderUuid)
	args = append(args, "--interactive")
	if stage1Hash != "" {
		args = append(args, "--stage1-hash="+stage1Hash)
	} else {
		args = append(args, "--stage1-name="+aci.manifest.Builder.Image.String())
	}

	for _, v := range aci.args.SetEnv.Strings() {
		args = append(args, "--set-env="+v)
	}
	args = append(args, builderHash)
	return args
}
예제 #13
0
func concatenateStringAndInt(a interface{}, b interface{}) (string, bool) {
	var aString string

	switch v := a.(type) {
	case string:
		aString = v
	case int64:
		aString = strconv.FormatInt(v, 10)
	case bool:
		aString = strconv.FormatBool(v)
	default:
		return "", false
	}

	switch v := b.(type) {
	case string:
		return aString + v, true
	case int64:
		return aString + strconv.FormatInt(v, 10), true
	case bool:
		return aString + strconv.FormatBool(v), true
	default:
		return "", false
	}
}
예제 #14
0
func (cmd *Activity) show(activityId string) {
	activity, err := activities.Activity(cmd.network, activityId)
	if nil != err {
		error_handler.ErrorExit(err)
	}

	table := terminal.NewTable([]string{"Id:", activity.Id})
	table.Add("DisplayName:", activity.DisplayName)
	table.Add("Description:", activity.Description)
	table.Add("EntityId:", activity.EntityId)
	table.Add("EntityDisplayName:", activity.EntityDisplayName)
	table.Add("Submitted:", time.Unix(activity.SubmitTimeUtc/1000, 0).Format(time.UnixDate))
	table.Add("Started:", time.Unix(activity.StartTimeUtc/1000, 0).Format(time.UnixDate))
	table.Add("Ended:", time.Unix(activity.EndTimeUtc/1000, 0).Format(time.UnixDate))
	table.Add("CurrentStatus:", activity.CurrentStatus)
	table.Add("IsError:", strconv.FormatBool(activity.IsError))
	table.Add("IsCancelled:", strconv.FormatBool(activity.IsCancelled))
	table.Add("SubmittedByTask:", activity.SubmittedByTask.Metadata.Id)
	if activity.Streams["stdin"].Metadata.Size > 0 ||
		activity.Streams["stdout"].Metadata.Size > 0 ||
		activity.Streams["stderr"].Metadata.Size > 0 ||
		activity.Streams["env"].Metadata.Size > 0 {
		table.Add("Streams:", fmt.Sprintf("stdin: %d, stdout: %d, stderr: %d, env %d",
			activity.Streams["stdin"].Metadata.Size,
			activity.Streams["stdout"].Metadata.Size,
			activity.Streams["stderr"].Metadata.Size,
			activity.Streams["env"].Metadata.Size))
	} else {
		table.Add("Streams:", "")
	}
	table.Add("DetailedStatus:", fmt.Sprintf("\"%s\"", activity.DetailedStatus))
	table.Print()
}
예제 #15
0
파일: balances.go 프로젝트: nikbyte/cgrates
func (b *Balance) SetValue(amount float64) {
	b.Value = amount
	b.Value = utils.Round(b.GetValue(), globalRoundingDecimals, utils.ROUNDING_MIDDLE)
	b.dirty = true

	// publish event
	accountId := ""
	allowNegative := ""
	disabled := ""
	if b.account != nil {
		accountId = b.account.Id
		allowNegative = strconv.FormatBool(b.account.AllowNegative)
		disabled = strconv.FormatBool(b.account.Disabled)
	}
	Publish(CgrEvent{
		"EventName":            utils.EVT_ACCOUNT_BALANCE_MODIFIED,
		"Uuid":                 b.Uuid,
		"Id":                   b.Id,
		"Value":                strconv.FormatFloat(b.Value, 'f', -1, 64),
		"ExpirationDate":       b.ExpirationDate.String(),
		"Weight":               strconv.FormatFloat(b.Weight, 'f', -1, 64),
		"DestinationIds":       b.DestinationIds,
		"RatingSubject":        b.RatingSubject,
		"Category":             b.Category,
		"SharedGroup":          b.SharedGroup,
		"TimingIDs":            b.TimingIDs,
		"Account":              accountId,
		"AccountAllowNegative": allowNegative,
		"AccountDisabled":      disabled,
	})
}
예제 #16
0
func (q *QueryOptions) String() string {
	u := &url.Values{}

	if q.AllowStale {
		u.Add("stale", strconv.FormatBool(q.AllowStale))
	}

	if q.Datacenter != "" {
		u.Add("dc", q.Datacenter)
	}

	if q.Near != "" {
		u.Add("near", q.Near)
	}

	if q.RequireConsistent {
		u.Add("consistent", strconv.FormatBool(q.RequireConsistent))
	}

	if q.WaitIndex != 0 {
		u.Add("index", strconv.FormatUint(q.WaitIndex, 10))
	}

	if q.WaitTime != 0 {
		u.Add("wait", q.WaitTime.String())
	}

	return u.Encode()
}
예제 #17
0
func (c Client) List(params *stripe.BitcoinReceiverListParams) *Iter {
	type receiverList struct {
		stripe.ListMeta
		Values []*stripe.BitcoinReceiver `json:"data"`
	}

	var body *url.Values
	var lp *stripe.ListParams

	if params != nil {
		body = &url.Values{}

		body.Add("filled", strconv.FormatBool(!params.NotFilled))
		body.Add("active", strconv.FormatBool(!params.NotActive))
		body.Add("uncaptured_funds", strconv.FormatBool(params.Uncaptured))

		params.AppendTo(body)
		lp = &params.ListParams
	}

	return &Iter{stripe.GetIter(lp, body, func(b url.Values) ([]interface{}, stripe.ListMeta, error) {
		list := &receiverList{}
		err := c.B.Call("GET", "/bitcoin/receivers", c.Key, &b, nil, list)

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}
func (node RefreshMatViewStmt) Fingerprint(ctx FingerprintContext, parentNode Node, parentFieldName string) {
	ctx.WriteString("RefreshMatViewStmt")

	if node.Concurrent {
		ctx.WriteString("concurrent")
		ctx.WriteString(strconv.FormatBool(node.Concurrent))
	}

	if node.Relation != nil {
		subCtx := FingerprintSubContext{}
		node.Relation.Fingerprint(&subCtx, node, "Relation")

		if len(subCtx.parts) > 0 {
			ctx.WriteString("relation")
			for _, part := range subCtx.parts {
				ctx.WriteString(part)
			}
		}
	}

	if node.SkipData {
		ctx.WriteString("skipData")
		ctx.WriteString(strconv.FormatBool(node.SkipData))
	}
}
예제 #19
0
파일: hdwallet.go 프로젝트: ThePiachu/gobcy
//GetAddrHDWallet returns addresses associated with
//a named HDWallet, associated with the API token/coin/chain.
//Offers 4 parameters for customization:
//  "used," if true will return only used addresses
//  "unused," if true will return only unused addresses
//  "zero", if true will return only zero balance addresses
//  "nonzero", if true will return only nonzero balance addresses
//"used" and "unused" cannot be true at the same time; the SDK will throw an error.
//"zero" and "nonzero" cannot be true at the same time; the SDK will throw an error.
func (api *API) GetAddrHDWallet(c appengine.Context, name string, used bool, unused bool, zero bool, nonzero bool) (addrs HDWallet, err error) {
	params := make(map[string]string)
	if used && unused {
		err = errors.New("GetAddrHDWallet: Unused and used cannot be the same")
		return
	}
	if zero && nonzero {
		err = errors.New("GetAddrHDWallet: Zero and nonzero cannot be the same")
		return
	}
	if used != unused {
		params["used"] = strconv.FormatBool(used)
	}
	if zero != nonzero {
		params["zerobalance"] = strconv.FormatBool(zero)
	}
	u, err := api.buildURLParams("/wallets/hd/"+name+"/addresses", params)
	resp, err := getResponse(c, u)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	//decode JSON into result
	dec := json.NewDecoder(resp.Body)
	err = dec.Decode(&addrs)
	return
}
예제 #20
0
파일: elb.go 프로젝트: cedmundo/goamz
func (elb *ELB) ModifyLoadBalancerAttributes(options *ModifyLoadBalancerAttributes) (resp *SimpleResp, err error) {
	params := makeParams("ModifyLoadBalancerAttributes")

	params["LoadBalancerName"] = options.LoadBalancerName
	params["LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled"] = strconv.FormatBool(options.LoadBalancerAttributes.CrossZoneLoadBalancingEnabled)
	if options.LoadBalancerAttributes.ConnectionSettingsIdleTimeout > 0 {
		params["LoadBalancerAttributes.ConnectionSettings.IdleTimeout"] = strconv.Itoa(int(options.LoadBalancerAttributes.ConnectionSettingsIdleTimeout))
	}
	if options.LoadBalancerAttributes.ConnectionDraining.Timeout > 0 {
		params["LoadBalancerAttributes.ConnectionDraining.Timeout"] = strconv.Itoa(int(options.LoadBalancerAttributes.ConnectionDraining.Timeout))
	}
	params["LoadBalancerAttributes.ConnectionDraining.Enabled"] = strconv.FormatBool(options.LoadBalancerAttributes.ConnectionDraining.Enabled)
	params["LoadBalancerAttributes.AccessLog.Enabled"] = strconv.FormatBool(options.LoadBalancerAttributes.AccessLog.Enabled)
	if options.LoadBalancerAttributes.AccessLog.Enabled {
		params["LoadBalancerAttributes.AccessLog.EmitInterval"] = strconv.Itoa(int(options.LoadBalancerAttributes.AccessLog.EmitInterval))
		params["LoadBalancerAttributes.AccessLog.S3BucketName"] = options.LoadBalancerAttributes.AccessLog.S3BucketName
		params["LoadBalancerAttributes.AccessLog.S3BucketPrefix"] = options.LoadBalancerAttributes.AccessLog.S3BucketPrefix
	}

	resp = &SimpleResp{}

	err = elb.query(params, resp)

	if err != nil {
		resp = nil
	}

	return
}
예제 #21
0
func main() {
	kingpin.Parse()
	client := artifactory.NewClientFromEnv()
	u, err := client.GetUserDetails(*user)
	if err != nil {
		fmt.Printf("%s\n", err)
		os.Exit(1)
	} else {
		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"Name", "Email", "Password", "Admin?", "Updatable?", "Last Logged In", "Internal Password Disabled?", "Realm", "Groups"})
		table.SetAutoWrapText(false)
		table.Append([]string{
			u.Name,
			u.Email,
			"<hidden>",
			strconv.FormatBool(u.Admin),
			strconv.FormatBool(u.ProfileUpdatable),
			u.LastLoggedIn,
			strconv.FormatBool(u.InternalPasswordDisabled),
			u.Realm,
			strings.Join(u.Groups, "\n"),
		})
		table.Render()
		os.Exit(0)
	}
}
예제 #22
0
func TestEvacuateFlags(t *testing.T) {
	defaults := NewEvacuateOptions(nil)

	tests := map[string]struct {
		flagName   string
		defaultVal string
	}{
		"dry run": {
			flagName:   flagDryRun,
			defaultVal: strconv.FormatBool(defaults.DryRun),
		},
		"force": {
			flagName:   flagForce,
			defaultVal: strconv.FormatBool(defaults.Force),
		},
		"grace period": {
			flagName:   flagGracePeriod,
			defaultVal: strconv.FormatInt(defaults.GracePeriod, 10),
		},
	}

	cmd := NewCommandManageNode(nil, ManageNodeCommandName, ManageNodeCommandName, nil)
	for _, v := range tests {
		testFlag(cmd, v.flagName, v.defaultVal, t)
	}
}
예제 #23
0
파일: dropbox.go 프로젝트: vichetuc/dropbox
// Metadata gets the metadata for a file or a directory.
// If list is true and src is a directory, immediate child will be sent in the Contents field.
// If include_deleted is true, entries deleted will be sent.
// hash is the hash of the contents of a directory, it is used to avoid sending data when directory did not change.
// rev is the specific revision to get the metadata from.
// limit is the maximum number of entries requested.
func (db *Dropbox) Metadata(src string, list bool, includeDeleted bool, hash, rev string, limit int) (*Entry, error) {
	var rv Entry
	var params *url.Values

	if limit <= 0 {
		limit = MetadataLimitDefault
	} else if limit > MetadataLimitMax {
		limit = MetadataLimitMax
	}
	params = &url.Values{
		"list":            {strconv.FormatBool(list)},
		"include_deleted": {strconv.FormatBool(includeDeleted)},
		"file_limit":      {strconv.FormatInt(int64(limit), 10)},
	}
	if len(rev) != 0 {
		params.Set("rev", rev)
	}
	if len(hash) != 0 {
		params.Set("hash", hash)
	}

	act := strings.Join([]string{"metadata", db.RootDirectory, src}, "/")
	err := db.doRequest("GET", act, params, &rv)
	return &rv, err
}
예제 #24
0
func (p *ListAsyncJobsParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["account"]; found {
		u.Set("account", v.(string))
	}
	if v, found := p.p["domainid"]; found {
		u.Set("domainid", v.(string))
	}
	if v, found := p.p["isrecursive"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("isrecursive", vv)
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["listall"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("listall", vv)
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	if v, found := p.p["startdate"]; found {
		u.Set("startdate", v.(string))
	}
	return u
}
예제 #25
0
파일: client.go 프로젝트: zkirill/stripe-go
func (c Client) New(params *stripe.RefundParams) (*stripe.Refund, error) {
	body := &url.Values{}

	if params.Amount > 0 {
		body.Add("amount", strconv.FormatUint(params.Amount, 10))
	}

	if params.Fee {
		body.Add("refund_application_fee", strconv.FormatBool(params.Fee))
	}

	if params.Transfer {
		body.Add("refund_transfer", strconv.FormatBool(params.Transfer))
	}

	if len(params.Reason) > 0 {
		body.Add("reason", string(params.Reason))
	}

	params.AppendTo(body)

	refund := &stripe.Refund{}
	err := c.B.Call("POST", fmt.Sprintf("/charges/%v/refunds", params.Charge), c.Key, body, &params.Params, refund)

	return refund, err
}
예제 #26
0
func addMantlLabels(app *marathon.App, pkgDef *packageDefinition) error {
	if app.Labels == nil {
		app.Labels = make(map[string]string)
	}
	app.Labels[packageNameKey] = pkgDef.name
	app.Labels[packageVersionKey] = pkgDef.version
	app.Labels[packageIndexKey] = pkgDef.release
	app.Labels[packageIsFrameworkKey] = strconv.FormatBool(pkgDef.framework)

	uninstallJson, err := pkgDef.UninstallJson()
	if err != nil {
		return err
	}
	app.Labels[packageUninstallKey] = base64.StdEncoding.EncodeToString([]byte(uninstallJson))

	if pkgDef.frameworkName != "" {
		app.Labels[packageFrameworkNameKey] = pkgDef.frameworkName
	}

	// copy DCOS_PACKAGE_FRAMEWORK_NAME if it exists
	if fwName, ok := app.Labels[dcosPackageFrameworkNameKey]; ok {
		app.Labels[packageFrameworkNameKey] = fwName
	}

	lb, err := pkgDef.LoadBalancer()
	if err == nil {
		app.Labels[traefikEnableKey] = strconv.FormatBool(lb == "external")
	} else {
		log.Warnf("Unable to retrieve load balancer configuration: %s", err.Error())
	}

	return nil
}
예제 #27
0
func handleLog(client *client.Client, namespace, podID string, logOptions *api.PodLogOptions, out io.Writer) error {
	// TODO: transform this into a PodLogOptions call
	req := client.RESTClient.Get().
		Namespace(namespace).
		Name(podID).
		Resource("pods").
		SubResource("log").
		Param("follow", strconv.FormatBool(logOptions.Follow)).
		Param("container", logOptions.Container).
		Param("previous", strconv.FormatBool(logOptions.Previous)).
		Param("timestamps", strconv.FormatBool(logOptions.Timestamps))

	if logOptions.SinceSeconds != nil {
		req.Param("sinceSeconds", strconv.FormatInt(*logOptions.SinceSeconds, 10))
	}
	if logOptions.SinceTime != nil {
		req.Param("sinceTime", logOptions.SinceTime.Format(time.RFC3339))
	}
	if logOptions.LimitBytes != nil {
		req.Param("limitBytes", strconv.FormatInt(*logOptions.LimitBytes, 10))
	}
	if logOptions.TailLines != nil {
		req.Param("tailLines", strconv.FormatInt(*logOptions.TailLines, 10))
	}
	readCloser, err := req.Stream()
	if err != nil {
		return err
	}

	defer readCloser.Close()
	_, err = io.Copy(out, readCloser)
	return err
}
예제 #28
0
func getClientProperties(c *model.Config) map[string]string {
	props := make(map[string]string)

	props["Version"] = model.CurrentVersion
	props["BuildNumber"] = model.BuildNumber
	props["BuildDate"] = model.BuildDate
	props["BuildHash"] = model.BuildHash

	props["SiteName"] = c.TeamSettings.SiteName
	props["EnableTeamCreation"] = strconv.FormatBool(c.TeamSettings.EnableTeamCreation)

	props["EnableOAuthServiceProvider"] = strconv.FormatBool(c.ServiceSettings.EnableOAuthServiceProvider)

	props["SegmentDeveloperKey"] = c.ServiceSettings.SegmentDeveloperKey
	props["GoogleDeveloperKey"] = c.ServiceSettings.GoogleDeveloperKey
	props["EnableIncomingWebhooks"] = strconv.FormatBool(c.ServiceSettings.EnableIncomingWebhooks)
	props["EnablePostUsernameOverride"] = strconv.FormatBool(c.ServiceSettings.EnablePostUsernameOverride)
	props["EnablePostIconOverride"] = strconv.FormatBool(c.ServiceSettings.EnablePostIconOverride)

	props["SendEmailNotifications"] = strconv.FormatBool(c.EmailSettings.SendEmailNotifications)
	props["EnableSignUpWithEmail"] = strconv.FormatBool(c.EmailSettings.EnableSignUpWithEmail)
	props["FeedbackEmail"] = c.EmailSettings.FeedbackEmail

	props["EnableSignUpWithGitLab"] = strconv.FormatBool(c.GitLabSettings.Enable)

	props["ShowEmailAddress"] = strconv.FormatBool(c.PrivacySettings.ShowEmailAddress)

	props["EnablePublicLink"] = strconv.FormatBool(c.FileSettings.EnablePublicLink)
	props["ProfileHeight"] = fmt.Sprintf("%v", c.FileSettings.ProfileHeight)
	props["ProfileWidth"] = fmt.Sprintf("%v", c.FileSettings.ProfileWidth)

	return props
}
func (p *ListDomainChildrenParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["id"]; found {
		u.Set("id", v.(string))
	}
	if v, found := p.p["isrecursive"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("isrecursive", vv)
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["listall"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("listall", vv)
	}
	if v, found := p.p["name"]; found {
		u.Set("name", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	return u
}
예제 #30
0
파일: alarms.go 프로젝트: jgoulah/go.fitbit
// AddAlarm is used to add a alarm to the users profile
// This method returns an object containing the created alarm if succesful
func (c *Client) AddAlarm(date time.Time, enabled, recurring bool, weekDays []string, label string, snoozeLength, snoozeCount, deviceID uint64) (*AddAlarm, error) {
	/*
	 * NOTE:
	 * This method is currently not available in the API
	 * When this method is called the server returns a 500 Internal server error
	 * The method is for the time begin unavailable
	 */
	// return nil, errors.New("not implemented yet")

	//Build arguments map
	dataArguments := map[string]string{
		"time":      date.Format("15:04-0700"),
		"enabled":   strconv.FormatBool(enabled),
		"recurring": strconv.FormatBool(recurring),
		"vibe":      "DEFAULT", //Only value for now
	}

	//Check for label
	if len(label) > 0 {
		dataArguments["label"] = label
	}

	//Check for snooze length
	if snoozeLength > 0 {
		dataArguments["snoozeLength"] = strconv.FormatUint(snoozeLength, 10)
	}

	//Check for snooze count
	if snoozeCount > 0 {
		dataArguments["snoozeCount"] = strconv.FormatUint(snoozeCount, 10)
	}

	splitWeekdays := ""
	if len(weekDays) > 0 {
		for i, day := range weekDays {
			if i > 0 {
				splitWeekdays += ","
			}
			splitWeekdays += day
		}
	}
	dataArguments["weekDays"] = "MONDAY"

	//Build an put request-URL
	requestURL := fmt.Sprintf("user/-/devices/tracker/%d/alarms.json", deviceID)
	responseBody, err := c.postData(requestURL, dataArguments)
	if err != nil {
		return nil, err
	}

	//Parse data
	addAlarm := &AddAlarm{}
	err = json.NewDecoder(responseBody).Decode(addAlarm)
	if err != nil {
		return nil, err
	}

	return addAlarm, nil

}