// This works for legacy configuration because our TOML is simply key/value.
// Will not work once we go hierarchical
516767
func readTomlFile(filePath string) (map[string]string, error) {
	configProps := map[string]string{}

	file, err := os.Open(filePath)
	if err != nil {
		return configProps, fmt.Errorf("could not load configuration file (%s): %v", filePath, err.Error())
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanLines)

	for scanner.Scan() {
		line := scanner.Text()
		if strings.Contains(line, "=") {
			tokens := strings.Split(scanner.Text(), "=")
			configProps[strings.Trim(tokens[0], " '")] = strings.Trim(tokens[1], " '")
		}
	}
	return configProps, nil
}
387827
func (m *Callback) ToRawInfo() interface{} {
	info := yaml.MapSlice{}
	if m == nil {
		return info
	}
	if m.Path != nil {
		for _, item := range m.Path {
			info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()})
		}
	}
	// &{Name:Path Type:NamedPathItem StringEnumValues:[] MapType:PathItem Repeated:true Pattern:^ Implicit:true Description:}
	if m.SpecificationExtension != nil {
		for _, item := range m.SpecificationExtension {
			info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()})
		}
	}
	// &{Name:SpecificationExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:}
	return info
}
876056
func main() {
	CheckArgs("<url>")
	url := os.Args[1]

	// Create a custom http(s) client with your config
	customClient := &http.Client{
		// accept any certificate (might be useful for testing)
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},

		// 15 second timeout
		Timeout: 15 * time.Second,

		// don't follow redirect
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	// Override http(s) default protocol to use our custom client
	client.InstallProtocol("https", githttp.NewClient(customClient))

	// Clone repository using the new client if the protocol is https://
	Info("git clone %s", url)

	r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: url})
	CheckIfError(err)

	// Retrieve the branch pointed by HEAD
	Info("git rev-parse HEAD")

	head, err := r.Head()
	CheckIfError(err)
	fmt.Println(head.Hash())
}
77793
func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) {
	if mapping, ok := value.(map[interface{}]interface{}); ok {
		dict := make(map[string]interface{})
		for key, entry := range mapping {
			str, ok := key.(string)
			if !ok {
				return nil, formatInvalidKeyError(keyPrefix, key)
			}
			var newKeyPrefix string
			if keyPrefix == "" {
				newKeyPrefix = str
			} else {
				newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str)
			}
			convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
			if err != nil {
				return nil, err
			}
			dict[str] = convertedEntry
		}
		return dict, nil
	}
	if list, ok := value.([]interface{}); ok {
		var convertedList []interface{}
		for index, entry := range list {
			newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index)
			convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
			if err != nil {
				return nil, err
			}
			convertedList = append(convertedList, convertedEntry)
		}
		return convertedList, nil
	}
	return value, nil
}
1179243
func (cfgSrcHandler *Handler) GetConfigurationByKeyAndDimensionInfo(key, dimensionInfo string) (interface{}, error) {
	var (
		configSrcVal interface{}
		actualValue  interface{}
		exist        bool
	)

	cfgSrcHandler.Lock()
	for _, v := range cfgSrcHandler.dimensionsInfoConfigurations {
		value, ok := v[dimensionInfo]
		if ok {
			actualValue, exist = value[key]
		}
	}
	cfgSrcHandler.Unlock()

	if exist {
		configSrcVal = actualValue
		return configSrcVal, nil
	}

	return nil, errors.New("key not exist")
}
387034
func (op *Operator) RaftGetConfiguration(args *structs.GenericRequest, reply *structs.RaftConfigurationResponse) error {
	if done, err := op.srv.forward("Operator.RaftGetConfiguration", args, args, reply); done {
		return err
	}

	// Check management permissions
	if aclObj, err := op.srv.ResolveToken(args.AuthToken); err != nil {
		return err
	} else if aclObj != nil && !aclObj.IsManagement() {
		return structs.ErrPermissionDenied
	}

	// We can't fetch the leader and the configuration atomically with
	// the current Raft API.
	future := op.srv.raft.GetConfiguration()
	if err := future.Error(); err != nil {
		return err
	}

	// Index the Nomad information about the servers.
	serverMap := make(map[raft.ServerAddress]serf.Member)
	for _, member := range op.srv.serf.Members() {
		valid, parts := isNomadServer(member)
		if !valid {
			continue
		}

		addr := (&net.TCPAddr{IP: member.Addr, Port: parts.Port}).String()
		serverMap[raft.ServerAddress(addr)] = member
	}

	// Fill out the reply.
	leader := op.srv.raft.Leader()
	reply.Index = future.Index()
	for _, server := range future.Configuration().Servers {
		node := "(unknown)"
		raftProtocolVersion := "unknown"
		if member, ok := serverMap[server.Address]; ok {
			node = member.Name
			if raftVsn, ok := member.Tags["raft_vsn"]; ok {
				raftProtocolVersion = raftVsn
			}
		}

		entry := &structs.RaftServer{
			ID:           server.ID,
			Node:         node,
			Address:      server.Address,
			Leader:       server.Address == leader,
			Voter:        server.Suffrage == raft.Voter,
			RaftProtocol: raftProtocolVersion,
		}
		reply.Servers = append(reply.Servers, entry)
	}
	return nil
}
516635
func (k Key) Parent() Key {
	n := k.List()
	if len(n) == 1 {
		return RawKey("/")
	}
	return NewKey(strings.Join(n[:len(n)-1], "/"))
}
390078
func (b UpdateMap) Put(ns, coll, key string, value []byte, version *version.Height) {
	b.PutValAndMetadata(ns, coll, key, value, nil, version)
}
339096
func (c *Capabilities) ToMap() (map[string]interface{}, error) {
	buf, err := json.Marshal(c)
	if err != nil {
		return nil, err
	}
	m := make(map[string]interface{})
	if err := json.Unmarshal(buf, &m); err != nil {
		return nil, err
	}
	return m, nil
}
846785
func (c *ctx) Value(key interface{}) interface{} {
	if key == ctxKey {
		return c
	}

	if k, ok := key.(string); ok {
		if val, exist := c.ParamOk(k); exist {
			return val
		}
	}

	return c.parent.Value(key)
}
423581
func (e *Encoder) valueToTree(mtype reflect.Type, mval reflect.Value) (*Tree, error) {
	if mtype.Kind() == reflect.Ptr {
		return e.valueToTree(mtype.Elem(), mval.Elem())
	}
	tval := e.nextTree()
	switch mtype.Kind() {
	case reflect.Struct:
		for i := 0; i < mtype.NumField(); i++ {
			mtypef, mvalf := mtype.Field(i), mval.Field(i)
			opts := tomlOptions(mtypef, e.annotation)
			if opts.include && (!opts.omitempty || !isZero(mvalf)) {
				val, err := e.valueToToml(mtypef.Type, mvalf)
				if err != nil {
					return nil, err
				}

				tval.SetWithOptions(opts.name, SetOptions{
					Comment:   opts.comment,
					Commented: opts.commented,
					Multiline: opts.multiline,
				}, val)
			}
		}
	case reflect.Map:
		keys := mval.MapKeys()
		if e.order == OrderPreserve && len(keys) > 0 {
			// Sorting []reflect.Value is not straight forward.
			//
			// OrderPreserve will support deterministic results when string is used
			// as the key to maps.
			typ := keys[0].Type()
			kind := keys[0].Kind()
			if kind == reflect.String {
				ikeys := make([]string, len(keys))
				for i := range keys {
					ikeys[i] = keys[i].Interface().(string)
				}
				sort.Strings(ikeys)
				for i := range ikeys {
					keys[i] = reflect.ValueOf(ikeys[i]).Convert(typ)
				}
			}
		}
		for _, key := range keys {
			mvalf := mval.MapIndex(key)
			val, err := e.valueToToml(mtype.Elem(), mvalf)
			if err != nil {
				return nil, err
			}
			if e.quoteMapKeys {
				keyStr, err := tomlValueStringRepresentation(key.String(), "", e.arraysOneElementPerLine)
				if err != nil {
					return nil, err
				}
				tval.SetPath([]string{keyStr}, val)
			} else {
				tval.Set(key.String(), val)
			}
		}
	}
	return tval, nil
}
1214245
func ToMap(ctx context.Context) map[string]interface{} {
	if ctx == nil {
		return map[string]interface{}{}
	}
	p := ctx.Value(constants.PropagateCtxKey)
	if p != nil {
		return p.(map[string]interface{})
	}
	return map[string]interface{}{}
}
235303
func (fs *KBFSOpsStandard) GetRootNodeMetadata(
	ctx context.Context, folderBranch data.FolderBranch) (
	NodeMetadata, *tlfhandle.Handle, error) {
	timeTrackerDone := fs.longOperationDebugDumper.Begin(ctx)
	defer timeTrackerDone()

	ops := fs.getOps(ctx, folderBranch, FavoritesOpNoChange)
	rootNode, _, _, err := ops.getRootNode(ctx)
	if err != nil {
		return NodeMetadata{}, nil, err
	}
	md, err := ops.GetNodeMetadata(ctx, rootNode)
	if err != nil {
		return NodeMetadata{}, nil, err
	}

	h, err := ops.GetTLFHandle(ctx, rootNode)
	if err != nil {
		return NodeMetadata{}, nil, err
	}
	return md, h, nil
}
532482
func main() {
	var addr, conf string
	flag.StringVar(&addr, "a", "127.0.0.1:9876", "`address` of server")
	flag.StringVar(&conf, "f", "server.json", "config `file` to use")
	flag.Parse()

	var id = new(core.Identity)
	data, err := ioutil.ReadFile(conf)
	if err != nil {
		exlib.Err(1, err, "reading config file")
	}

	err = json.Unmarshal(data, id)
	if err != nil {
		exlib.Err(1, err, "parsing config file")
	}

	tr, err := transport.New(exlib.Before, id)
	if err != nil {
		exlib.Err(1, err, "creating transport")
	}

	l, err := transport.Listen(addr, tr)
	if err != nil {
		exlib.Err(1, err, "setting up listener")
	}

	var errChan = make(chan error, 0)
	go func(ec <-chan error) {
		for {
			err, ok := <-ec
			if !ok {
				log.Warning("error channel closed, future errors will not be reported")
				break
			}
			log.Errorf("auto update error: %v", err)
		}
	}(errChan)

	log.Info("setting up auto-update")
	go l.AutoUpdate(nil, errChan)

	log.Info("listening on ", addr)
	exlib.Warn(serve(l), "serving listener")
}
502167
func GetPathRelativeToConfig(configuration *viper.Viper, key string) string {
	configFile := configuration.ConfigFileUsed()
	p := configuration.GetString(key)
	if p == "" || filepath.IsAbs(p) {
		return p
	}
	return filepath.Clean(filepath.Join(filepath.Dir(configFile), p))
}
859765
func (d *Docker) TOML() string {
	return fmt.Sprintf(`[[inputs.%s]]	
  ## Docker Endpoint
  ##   To use TCP, set endpoint = "tcp://[ip]:[port]"
  ##   To use environment variables (ie, docker-machine), set endpoint = "ENV"
  ##   exp: unix:///var/run/docker.sock
  endpoint = "%s"

  ## Set to true to collect Swarm metrics(desired_replicas, running_replicas)
  gather_services = false

  ## Only collect metrics for these containers, collect all if empty
  container_names = []

  ## Containers to include and exclude. Globs accepted.
  ## Note that an empty array for both will include all containers
  container_name_include = []
  container_name_exclude = []

  ## Container states to include and exclude. Globs accepted.
  ## When empty only containers in the "running" state will be captured.
  # container_state_include = []
  # container_state_exclude = []

  ## Timeout for docker list, info, and stats commands
  timeout = "5s"

  ## Whether to report for each container per-device blkio (8:0, 8:1...) and
  ## network (eth0, eth1, ...) stats or not
  perdevice = true

  ## Whether to report for each container total blkio and network stats or not
  total = false
  
  ## Which environment variables should we use as a tag
  ##tag_env = ["JAVA_HOME", "HEAP_SIZE"]
  ## docker labels to include and exclude as tags.  Globs accepted.
  ## Note that an empty array for both will include all labels as tags
  docker_label_include = []
  docker_label_exclude = []
`, d.PluginName(), d.Endpoint)
}
19833
func Metadatify(i interface{}) (Metadata, error) {
	value := reflect.ValueOf(i)
	if value.Kind() == reflect.Map {
		m := map[string]interface{}{}
		for _, k := range value.MapKeys() {
			m[k.String()] = value.MapIndex(k).Interface()
		}
		return Metadata(m), nil
	}
	return nil, errors.New("is not a map")
}