// doCredAPI makes userless requests to the Foursquare API, which have a larger
// quota than user requests for some endpoints.
// https://developer.foursquare.com/overview/auth#userless
// https://developer.foursquare.com/overview/ratelimits
320494
func (im *imp) doCredAPI(ctx context.Context, clientID, clientSecret string, result interface{}, apiPath string, keyval ...string) error {
	form := url.Values{}
	form.Set("client_id", clientID)
	form.Set("client_secret", clientSecret)
	return im.doAPI(ctx, form, result, apiPath, keyval...)
}
1341957
func NewAPI(
	backend Backend,
	authorizer facade.Authorizer,
	blockChecker BlockChecker,
) (*API, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	return &API{
		backend:    backend,
		authorizer: authorizer,
		check:      blockChecker,
	}, nil
}
773326
func TokenAuthorizedWhere(a *Authorization) func(DocumentIndex, DocumentDecorator) ([]ID, error) {
	// TODO(desa): what to do about retrieving all documents using auth? (e.g. write/read:documents/*)
	var ids []ID
	return func(idx DocumentIndex, _ DocumentDecorator) ([]ID, error) {
		if !a.IsActive() {
			return nil, &Error{
				Code: EUnauthorized,
				Msg:  "authorizer cannot access documents",
			}
		}

		for _, p := range a.Permissions {
			if p.Resource.Type == DocumentsResourceType && p.Resource.OrgID != nil {
				oids, err := idx.GetAccessorsDocuments("org", *p.Resource.OrgID)
				if err != nil {
					return nil, err
				}
				ids = append(ids, oids...)
			}

			if p.Resource.Type == DocumentsResourceType && p.Resource.ID != nil {
				ids = append(ids, *p.Resource.ID)
			}
		}

		return ids, nil
	}
}
510731
func (c *Context) GetAPI() (coreiface.CoreAPI, error) {
	if c.api == nil {
		n, err := c.GetNode()
		if err != nil {
			return nil, err
		}
		fetchBlocks := true
		if c.Gateway {
			cfg, err := c.GetConfig()
			if err != nil {
				return nil, err
			}
			fetchBlocks = !cfg.Gateway.NoFetch
		}

		c.api, err = coreapi.NewCoreAPI(n, options.Api.FetchBlocks(fetchBlocks))
		if err != nil {
			return nil, err
		}
	}
	return c.api, nil
}
1011108
func (b *Builder) WithAPI(api *api.API) *Builder {
	b.settings.API = api
	return b
}
1323612
func NewAPI(st *state.State, res facade.Resources, auth facade.Authorizer) (SubnetsAPI, error) {
	stateshim, err := networkingcommon.NewStateShim(st)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return newAPIWithBacking(stateshim, state.CallContext(st), res, auth)
}
821533
func NewApi(runningInKubernetes bool, metricSink *metricsink.MetricSink, historicalSource core.HistoricalSource, disableMetricExport bool) *Api {
	gkeMetrics := make(map[string]core.MetricDescriptor)
	gkeLabels := make(map[string]core.LabelDescriptor)
	for _, val := range core.StandardMetrics {
		gkeMetrics[val.Name] = val.MetricDescriptor
	}
	for _, val := range core.LabeledMetrics {
		gkeMetrics[val.Name] = val.MetricDescriptor
	}
	gkeMetrics[core.MetricCpuLimit.Name] = core.MetricCpuLimit.MetricDescriptor
	gkeMetrics[core.MetricMemoryLimit.Name] = core.MetricMemoryLimit.MetricDescriptor

	for _, val := range core.CommonLabels() {
		gkeLabels[val.Key] = val
	}
	for _, val := range core.ContainerLabels() {
		gkeLabels[val.Key] = val
	}
	for _, val := range core.PodLabels() {
		gkeLabels[val.Key] = val
	}

	return &Api{
		runningInKubernetes: runningInKubernetes,
		metricSink:          metricSink,
		historicalSource:    historicalSource,
		gkeMetrics:          gkeMetrics,
		gkeLabels:           gkeLabels,
		disabled:            disableMetricExport,
	}
}
1368665
func HostApi(apiType HostApiType) (*HostApiInfo, error) {
	hosts, err := HostApis()
	if err != nil {
		return nil, err
	}
	i := C.Pa_HostApiTypeIdToHostApiIndex(C.PaHostApiTypeId(apiType))
	if i < 0 {
		return nil, newError(C.PaError(i))
	}
	return hosts[i], nil
}
264135
func NewAPI(caller base.APICaller) *API {
	if caller == nil {
		panic("caller is nil")
	}
	facadeCaller := base.NewFacadeCaller(caller, instancePollerFacade)
	return &API{
		ModelWatcher: common.NewModelWatcher(facadeCaller),
		facade:       facadeCaller,
	}
}
764380
func (c *branchCommand) getAPI() (BranchCommandAPI, error) {
	if c.api != nil {
		return c.api, nil
	}
	api, err := c.NewAPIRoot()
	if err != nil {
		return nil, errors.Annotate(err, "opening API connection")
	}
	client := modelgeneration.NewClient(api)
	return client, nil
}
1234177
func GetApi(env cmds.Environment, req *cmds.Request) (coreiface.CoreAPI, error) {
	ctx, ok := env.(*commands.Context)
	if !ok {
		return nil, fmt.Errorf("expected env to be of type %T, got %T", ctx, env)
	}

	offline, _ := req.Options["offline"].(bool)
	if !offline {
		offline, _ = req.Options["local"].(bool)
		if offline {
			log.Errorf("Command '%s', --local is deprecated, use --offline instead", strings.Join(req.Path, " "))
		}
	}
	api, err := ctx.GetAPI()
	if err != nil {
		return nil, err
	}
	if offline {
		return api.WithOptions(options.Api.Offline(offline))
	}

	return api, nil
}
144134
func AuthorizedWhere(a Authorizer) func(DocumentIndex, DocumentDecorator) ([]ID, error) {
	switch t := a.(type) {
	case *Authorization:
		return TokenAuthorizedWhere(t)
	}

	var ids []ID
	return func(idx DocumentIndex, _ DocumentDecorator) ([]ID, error) {
		dids, err := idx.GetAccessorsDocuments("user", a.GetUserID())
		if err != nil {
			return nil, err
		}

		ids = append(ids, dids...)

		orgIDs, err := idx.UsersOrgs(a.GetUserID())
		if err != nil {
			return nil, err
		}

		for _, orgID := range orgIDs {
			dids, err := idx.GetAccessorsDocuments("org", orgID)
			if err != nil {
				return nil, err
			}

			ids = append(ids, dids...)
		}

		// TODO(desa): we should probably dedupe this list eventually.
		return ids, nil
	}
}
1035855
func DocsEdit() error {
	mg.SerialDeps(DocsInstallRequirements,
		docsCopySourceTemplatesToDocs)

	editCommandArgs := []string{
		"server",
		"--disableFastRender",
		"--watch",
		"--forceSyncStatic",
		"--verbose",
	}
	go func() {
		spartamage.Log("Waiting for docs to build...")
		time.Sleep(3 * time.Second)
		browser.OpenURL("http://localhost:1313")
	}()
	return runHugoCommand(editCommandArgs...)
}
691881
func createAPI(
	st metadataAccess,
	newEnviron func() (environs.Environ, error),
	resources facade.Resources,
	authorizer facade.Authorizer,
) (*API, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	admin, err := authorizer.HasPermission(permission.SuperuserAccess, st.ControllerTag())
	if err != nil {
		return nil, common.ErrPerm
	}
	if !admin {
		return nil, common.ErrPerm
	}

	return &API{
		metadata:   st,
		newEnviron: newEnviron,
	}, nil
}
130818
func NewAPI(fileStore *storage.FileStore, dns Resolver, feedHandler *feed.Handler, pk *ecdsa.PrivateKey) (self *API) {
	self = &API{
		fileStore: fileStore,
		dns:       dns,
		feed:      feedHandler,
		Decryptor: func(ctx context.Context, credentials string) DecryptFunc {
			return self.doDecrypt(ctx, credentials, pk)
		},
	}
	return
}
884615
func (api *ForceAPI) Limits() (data LimitsResponse, err error) {

	result, err := api.Connection.Get("/limits/")

	if err != nil {
		return LimitsResponse{}, err
	}

	err = json.Unmarshal(result, &data)

	if err != nil {
		return LimitsResponse{}, err
	}

	return data, nil
}
272094
func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy {
	return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
		if len(via) >= noOfRedirect {
			return fmt.Errorf("stopped after %d redirects", noOfRedirect)
		}

		checkHostAndAddHeaders(req, via[0])

		return nil
	})
}