_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q180800 | BudgetAlertLocator | test | func (api *API) BudgetAlertLocator(href string) *BudgetAlertLocator {
return &BudgetAlertLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180801 | CloudBillLocator | test | func (api *API) CloudBillLocator(href string) *CloudBillLocator {
return &CloudBillLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180802 | CloudBillMetricLocator | test | func (api *API) CloudBillMetricLocator(href string) *CloudBillMetricLocator {
return &CloudBillMetricLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180803 | CurrentUserLocator | test | func (api *API) CurrentUserLocator(href string) *CurrentUserLocator {
return &CurrentUserLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180804 | InstanceCombinationLocator | test | func (api *API) InstanceCombinationLocator(href string) *InstanceCombinationLocator {
return &InstanceCombinationLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180805 | InstanceMetricLocator | test | func (api *API) InstanceMetricLocator(href string) *InstanceMetricLocator {
return &InstanceMetricLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180806 | InstanceUsagePeriodLocator | test | func (api *API) InstanceUsagePeriodLocator(href string) *InstanceUsagePeriodLocator {
return &InstanceUsagePeriodLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180807 | PatternLocator | test | func (api *API) PatternLocator(href string) *PatternLocator {
return &PatternLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180808 | ReservedInstanceLocator | test | func (api *API) ReservedInstanceLocator(href string) *ReservedInstanceLocator {
return &ReservedInstanceLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180809 | ReservedInstancePurchaseLocator | test | func (api *API) ReservedInstancePurchaseLocator(href string) *ReservedInstancePurchaseLocator {
return &ReservedInstancePurchaseLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180810 | ScenarioLocator | test | func (api *API) ScenarioLocator(href string) *ScenarioLocator {
return &ScenarioLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180811 | ScheduledReportLocator | test | func (api *API) ScheduledReportLocator(href string) *ScheduledReportLocator {
return &ScheduledReportLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180812 | TempInstancePriceLocator | test | func (api *API) TempInstancePriceLocator(href string) *TempInstancePriceLocator {
return &TempInstancePriceLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180813 | UserSettingLocator | test | func (api *API) UserSettingLocator(href string) *UserSettingLocator {
return &UserSettingLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180814 | readAllAsync | test | func readAllAsync(f io.ReadCloser) (*[]byte, chan struct{}) {
done := make(chan struct{}, 1) // signal that the read is done
var buf []byte // placeholder buffer for the result
go func() {
var err error
buf, err = ioutil.ReadAll(f)
if err != nil {
buf = make([]byte, 0)
}
f.Close()
done <- struct{}{}
}()
return &buf, done
} | go | {
"resource": ""
} |
q180815 | extractArg | test | func extractArg(name string, args []string) (string, []string) {
var val string
var newArgs []string
var skip bool
for i, a := range args {
if skip {
skip = false
continue
}
if strings.Contains(a, "=") {
elems := strings.SplitN(a, "=", 2)
if elems[0] == name {
val = elems[1]
} else {
newArgs = append(newArgs, a)
}
} else if a == name && len(args) > (i+1) {
val = args[i+1]
skip = true
} else {
newArgs = append(newArgs, a)
}
}
return val, newArgs
} | go | {
"resource": ""
} |
q180816 | write | test | func write(b []byte) {
f, err := os.OpenFile(output, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fail("failed to open output file")
}
f.Write(b)
f.WriteString("\n")
f.Close()
} | go | {
"resource": ""
} |
q180817 | AppliedPolicyLocator | test | func (api *API) AppliedPolicyLocator(href string) *AppliedPolicyLocator {
return &AppliedPolicyLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180818 | ApprovalLocator | test | func (api *API) ApprovalLocator(href string) *ApprovalLocator {
return &ApprovalLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180819 | IncidentLocator | test | func (api *API) IncidentLocator(href string) *IncidentLocator {
return &IncidentLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180820 | PolicyTemplateLocator | test | func (api *API) PolicyTemplateLocator(href string) *PolicyTemplateLocator {
return &PolicyTemplateLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180821 | PublishedTemplateLocator | test | func (api *API) PublishedTemplateLocator(href string) *PublishedTemplateLocator {
return &PublishedTemplateLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180822 | DebugCookbookPathLocator | test | func (api *API) DebugCookbookPathLocator(href string) *DebugCookbookPathLocator {
return &DebugCookbookPathLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180823 | DockerControlLocator | test | func (api *API) DockerControlLocator(href string) *DockerControlLocator {
return &DockerControlLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180824 | EnvLocator | test | func (api *API) EnvLocator(href string) *EnvLocator {
return &EnvLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180825 | LoginControlLocator | test | func (api *API) LoginControlLocator(href string) *LoginControlLocator {
return &LoginControlLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180826 | ProcLocator | test | func (api *API) ProcLocator(href string) *ProcLocator {
return &ProcLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180827 | Rl10Locator | test | func (api *API) Rl10Locator(href string) *Rl10Locator {
return &Rl10Locator{Href(href), api}
} | go | {
"resource": ""
} |
q180828 | TSSLocator | test | func (api *API) TSSLocator(href string) *TSSLocator {
return &TSSLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180829 | TSSControlLocator | test | func (api *API) TSSControlLocator(href string) *TSSControlLocator {
return &TSSControlLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180830 | TSSPluginLocator | test | func (api *API) TSSPluginLocator(href string) *TSSPluginLocator {
return &TSSPluginLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180831 | NewAngularWriter | test | func NewAngularWriter() (*AngularWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"path": path,
"mandatory": mandatory,
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(angularTmpl)
if err != nil {
return nil, err
}
return &AngularWriter{
angularTmpl: resourceT,
}, nil
} | go | {
"resource": ""
} |
q180832 | WriteResource | test | func (c *AngularWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
return c.angularTmpl.Execute(w, resource)
} | go | {
"resource": ""
} |
q180833 | path | test | func path(a *gen.Action) string {
pattern := a.PathPatterns[0]
vars := pattern.Variables
ivars := make([]interface{}, len(vars))
for i, v := range vars {
ivars[i] = interface{}(":" + v)
}
return fmt.Sprintf(pattern.Pattern, ivars...)
} | go | {
"resource": ""
} |
q180834 | mandatory | test | func mandatory(a gen.Action, param string) bool {
for _, p := range a.Params {
if p.Name == param {
return p.Mandatory
}
}
panic("praxisgen bug: Unknown param " + param + " for action " + a.Name)
} | go | {
"resource": ""
} |
q180835 | New | test | func New(host string, auth Authenticator) *API {
client := httpclient.New()
if strings.HasPrefix(host, "http://") {
host = host[7:]
} else if strings.HasPrefix(host, "https://") {
host = host[8:]
}
a := &API{
Auth: auth,
Host: host,
Client: client,
}
if auth != nil {
auth.SetHost(host)
}
return a
} | go | {
"resource": ""
} |
q180836 | FromCommandLine | test | func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
var client *API
ss := strings.HasPrefix(cmdLine.Command, "ss")
if cmdLine.RL10 {
var err error
if client, err = NewRL10(); err != nil {
return nil, err
}
} else if cmdLine.OAuthToken != "" {
auth := NewOAuthAuthenticator(cmdLine.OAuthToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.OAuthAccessToken != "" {
auth := NewTokenAuthenticator(cmdLine.OAuthAccessToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.APIToken != "" {
auth := NewInstanceAuthenticator(cmdLine.APIToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.Username != "" && cmdLine.Password != "" {
auth := NewBasicAuthenticator(cmdLine.Username, cmdLine.Password, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else {
// No auth, used by tests
client = New(cmdLine.Host, nil)
httpclient.Insecure = true
}
if !cmdLine.ShowHelp && !cmdLine.NoAuth {
if cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && cmdLine.Username == "" && !cmdLine.RL10 {
return nil, fmt.Errorf("Missing authentication information, use '--email EMAIL --password PWD', '--token TOKEN' or 'setup'")
}
if cmdLine.Verbose || cmdLine.Dump == "debug" {
httpclient.DumpFormat = httpclient.Debug
}
if cmdLine.Dump == "json" {
httpclient.DumpFormat = httpclient.JSON
}
if cmdLine.Dump == "record" {
httpclient.DumpFormat = httpclient.JSON | httpclient.Record
}
if cmdLine.Verbose {
httpclient.DumpFormat |= httpclient.Verbose
}
client.FetchLocationResource = cmdLine.FetchResource
}
return client, nil
} | go | {
"resource": ""
} |
q180837 | CanAuthenticate | test | func (a *API) CanAuthenticate() error {
res := a.Auth.CanAuthenticate(a.Host)
return res
} | go | {
"resource": ""
} |
q180838 | Encrypt | test | func Encrypt(text string) (string, error) {
bytes := []byte(text)
key := seekret()
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
b := encodeBase64(bytes)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], b)
return string(encodeBase64(ciphertext)), nil
} | go | {
"resource": ""
} |
q180839 | Decrypt | test | func Decrypt(text string) (string, error) {
if text == "" {
return "", nil
}
key := seekret()
bytes := decodeBase64([]byte(text))
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(bytes) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := bytes[:aes.BlockSize]
bytes = bytes[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(bytes, bytes)
return string(decodeBase64(bytes)), nil
} | go | {
"resource": ""
} |
q180840 | guessType | test | func (a *APIAnalyzer) guessType(ec EvalCtx, d *Definition, refID string) string {
// First get the type name and and view from the swagger reference definition
// name -- are a few cases where that's the only place that has the view
if t, ok := a.TypeOverrides[refID]; ok {
return t
}
var name, view string
if strings.Contains(refID, "RequestBody") {
bits := strings.Split(refID, "RequestBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else if strings.Contains(refID, "ResponseBody") {
bits := strings.Split(refID, "ResponseBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else {
name = refID
}
// Now try and get it from the media type -- this is preferred if its set.
if mt := mediaType(d.Title); mt != "" {
if strings.Contains(mt, "application") {
bits := strings.Split(mt, ".")
name := bits[len(bits)-1]
attrs := mediaTypeAttrs(d.Title)
if attrs["type"] != "" {
name += "_" + attrs["type"]
}
if attrs["view"] != "" && attrs["view"] != "default" {
name += "_" + attrs["view"]
} else if view != "" {
name += "_" + view
}
dbg("DEBUG media type refID:%#v title:%#v name:%#v view:%#v -> type:%#v\n", refID, d.Title, name, view, name)
return toTypeName(name)
} else if strings.Contains(mt, "text/") {
return "string"
} else {
fail("Don't know how to handle media type %s", mt)
}
}
if view != "" {
return name + "_" + view
}
return name
} | go | {
"resource": ""
} |
q180841 | addType | test | func (a *APIAnalyzer) addType(ec EvalCtx, dt *gen.ObjectDataType, r Ref) {
a.api.NeedJSON = true
if a.refByType[dt.TypeName] == r.ID() {
return
}
if other, ok := a.api.Types[dt.TypeName]; ok {
if !ec.IsResult {
// If its an input parameter, fix the collision by amending this types name
dt.TypeName += "Param"
if a.refByType[dt.TypeName] == r.ID() {
return
}
}
oldFields := []string{}
newFields := []string{}
for _, f := range other.Fields {
oldFields = append(oldFields, f.Name)
}
for _, f := range dt.Fields {
newFields = append(newFields, f.Name)
}
use := "Old"
if len(newFields) > len(oldFields) {
use = "New"
}
if strings.Join(oldFields, ",") != strings.Join(newFields, ",") {
warn("Warning: Type collision when adding new type %s!\n New: id %s fields %v\n Old: id %s fields %v\n Using %s, which has more fields\n",
dt.TypeName, r.ID(), newFields, a.refByType[dt.TypeName], oldFields, use)
}
if use == "Old" {
return
}
}
dbg("DEBUG NEW TYPE %s\n", prettify(dt))
a.refByType[dt.TypeName] = r.ID()
a.api.Types[dt.TypeName] = dt
} | go | {
"resource": ""
} |
q180842 | extractCmdLineParams | test | func extractCmdLineParams(a *gen.ActionParam, root string, seen map[string]*[]*gen.ActionParam, parentNotMandatory bool) []*gen.ActionParam {
switch t := a.Type.(type) {
case *gen.BasicDataType, *gen.EnumerableDataType, *gen.UploadDataType:
dup := gen.ActionParam{
Name: a.Name,
QueryName: root,
Description: a.Description,
VarName: a.VarName,
Location: a.Location,
Type: a.Type,
Mandatory: a.Mandatory && !parentNotMandatory, // yay for double negations!
NonBlank: a.NonBlank,
Regexp: a.Regexp,
ValidValues: a.ValidValues,
Min: a.Min,
Max: a.Max,
}
return []*gen.ActionParam{&dup}
case *gen.ArrayDataType:
p := t.ElemType
eq, ok := seen[p.Name]
if !ok {
eq = &[]*gen.ActionParam{}
seen[p.Name] = eq
*eq = extractCmdLineParams(p, root+"[]", seen, parentNotMandatory || !a.Mandatory)
}
return *eq
case *gen.ObjectDataType:
params := []*gen.ActionParam{}
for _, f := range t.Fields {
eq, ok := seen[f.Name]
if !ok {
eq = &[]*gen.ActionParam{}
seen[f.Name] = eq
*eq = extractCmdLineParams(f, fmt.Sprintf("%s[%s]", root, f.Name), seen, parentNotMandatory || !a.Mandatory)
}
params = append(params, *eq...)
}
return params
}
return nil
} | go | {
"resource": ""
} |
q180843 | NewMetadataWriter | test | func NewMetadataWriter() (*MetadataWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"join": strings.Join,
"commandLine": commandLine,
"toStringArray": toStringArray,
"flagType": flagType,
"location": location,
"escapeBackticks": escapeBackticks,
}
headerT, err := template.New("header-metadata").Funcs(funcMap).Parse(headerMetadataTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-metadata").Funcs(funcMap).Parse(resourceMetadataTmpl)
if err != nil {
return nil, err
}
return &MetadataWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
} | go | {
"resource": ""
} |
q180844 | WriteHeader | test | func (c *MetadataWriter) WriteHeader(pkg string, w io.Writer) error {
return c.headerTmpl.Execute(w, pkg)
} | go | {
"resource": ""
} |
q180845 | WriteMetadata | test | func (c *MetadataWriter) WriteMetadata(d *gen.APIDescriptor, w io.Writer) error {
resources := make([]*gen.Resource, len(d.ResourceNames))
for i, n := range d.ResourceNames {
resources[i] = d.Resources[n]
}
return c.resourceTmpl.Execute(w, resources)
} | go | {
"resource": ""
} |
q180846 | location | test | func location(p *gen.ActionParam) string {
switch p.Location {
case gen.PathParam:
return "metadata.PathParam"
case gen.QueryParam:
return "metadata.QueryParam"
case gen.PayloadParam:
return "metadata.PayloadParam"
default:
return ""
}
} | go | {
"resource": ""
} |
q180847 | New | test | func New(host string, auth rsapi.Authenticator) *API {
return fromAPI(rsapi.New(host, auth))
} | go | {
"resource": ""
} |
q180848 | fromAPI | test | func fromAPI(api *rsapi.API) *API {
api.Metadata = GenMetadata
return &API{api}
} | go | {
"resource": ""
} |
q180849 | BuildRequest | test | func (a *API) BuildRequest(resource, action, href string, params rsapi.APIParams) (*http.Request, error) {
// First lookup metadata
res, ok := GenMetadata[resource]
if !ok {
return nil, fmt.Errorf("No resource with name '%s'", resource)
}
act := res.GetAction(action)
if act == nil {
return nil, fmt.Errorf("No action with name '%s' on %s", action, resource)
}
// Now lookup action request HTTP method, url, params and payload.
vars, err := res.ExtractVariables(href)
if err != nil {
return nil, err
}
actionURL, err := act.URL(vars)
if err != nil {
return nil, err
}
_, queryParams := rsapi.IdentifyParams(act, params)
return a.BuildHTTPRequest("GET", actionURL.Path, "1.6", queryParams, nil)
} | go | {
"resource": ""
} |
q180850 | setupMetadata | test | func setupMetadata() (result map[string]*metadata.Resource) {
result = make(map[string]*metadata.Resource)
for n, r := range cac.GenMetadata {
result[n] = r
}
return
} | go | {
"resource": ""
} |
q180851 | NewDisplayer | test | func NewDisplayer(resp *http.Response) (*Displayer, error) {
defer resp.Body.Close()
js, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read response (%s)", err)
}
disp := Displayer{response: resp, body: string(js)}
if len(js) > 2 {
err = json.Unmarshal(js, &disp.RawOutput)
if err != nil {
disp.RawOutput = string(js)
}
}
return &disp, nil
} | go | {
"resource": ""
} |
q180852 | ApplySingleExtract | test | func (d *Displayer) ApplySingleExtract(extract string) error {
if err := d.ApplyExtract(extract, true); err != nil {
return err
}
outputs := d.RawOutput.([]interface{})
if len(outputs) != 1 {
d.RawOutput = nil
return fmt.Errorf("JSON selector '%s' returned %d instead of one value",
extract, len(outputs))
}
if len(outputs) == 0 {
d.RawOutput = ""
} else {
switch v := outputs[0].(type) {
case nil:
d.RawOutput = ""
case float64, bool:
d.RawOutput = fmt.Sprint(v)
case string:
d.RawOutput = v
default:
d.RawOutput = v
}
d.RawOutput = outputs[0]
}
return nil
} | go | {
"resource": ""
} |
q180853 | ApplyExtract | test | func (d *Displayer) ApplyExtract(selector string, js bool) error {
parser, err := jsonselect.CreateParserFromString(d.body)
if err != nil {
return fmt.Errorf("Failed to load response JSON: %s, JSON was:\n%s", err, d.body)
}
outputs, err := parser.GetValues(selector)
if !js {
out := ""
for _, o := range outputs {
b, _ := json.Marshal(o)
out += string(b) + "\n"
}
d.RawOutput = out
} else {
d.RawOutput = outputs
}
if err != nil {
return fmt.Errorf("Failed to apply JSON selector '%s' to response: %s, JSON was:\n%s",
selector, err, d.body)
}
return nil
} | go | {
"resource": ""
} |
q180854 | ApplyHeaderExtract | test | func (d *Displayer) ApplyHeaderExtract(header string) error {
d.RawOutput = d.response.Header.Get(header)
if d.RawOutput == "" {
return fmt.Errorf("Response does not contain the '%s' header", header)
}
return nil
} | go | {
"resource": ""
} |
q180855 | Output | test | func (d *Displayer) Output() string {
output := d.RawOutput
if output == nil {
return ""
}
if outputStr, ok := d.RawOutput.(string); ok {
suffix := ""
if d.prettify {
suffix = "\n"
}
return outputStr + suffix
}
var out string
var err error
if d.prettify {
var b []byte
b, err = json.MarshalIndent(output, "", " ")
if err == nil {
out = string(b) + "\n"
}
} else {
var b []byte
b, err = json.Marshal(output)
out = string(b)
}
if err != nil {
fm := "%v"
if d.prettify {
fm += "\n"
}
return fmt.Sprintf(fm, output)
}
return out
} | go | {
"resource": ""
} |
q180856 | NewAPIAnalyzer | test | func NewAPIAnalyzer(resources map[string]interface{}, attributeTypes map[string]string) *APIAnalyzer {
return &APIAnalyzer{
rawResources: resources,
attributeTypes: attributeTypes,
rawTypes: make(map[string][]*gen.ObjectDataType),
}
} | go | {
"resource": ""
} |
q180857 | Analyze | test | func (a *APIAnalyzer) Analyze() *gen.APIDescriptor {
a.AnalyzeAliases()
var descriptor = &gen.APIDescriptor{
Resources: make(map[string]*gen.Resource),
Types: make(map[string]*gen.ObjectDataType),
}
var rawResourceNames = make([]string, len(a.rawResources))
var idx = 0
for n := range a.rawResources {
rawResourceNames[idx] = n
idx++
}
sort.Strings(rawResourceNames)
for _, name := range rawResourceNames {
var resource = a.rawResources[name]
a.AnalyzeResource(name, resource, descriptor)
}
descriptor.FinalizeTypeNames(a.rawTypes)
return descriptor
} | go | {
"resource": ""
} |
q180858 | AnalyzeAliases | test | func (a *APIAnalyzer) AnalyzeAliases() {
for from, to := range aliases {
splits := strings.SplitN(from, "#", 2)
fromResName := splits[0]
fromActionName := splits[1]
splits = strings.SplitN(to, "#", 2)
toResName := splits[0]
toActionName := splits[1]
fromRes := a.rawResources[fromResName]
fromAct := fromRes.(map[string]interface{})["methods"].(map[string]interface{})[fromActionName].(map[string]interface{})
toRes := a.rawResources[toResName]
toAct := toRes.(map[string]interface{})["methods"].(map[string]interface{})[toActionName].(map[string]interface{})
fromAct["parameters"] = toAct["parameters"]
fromAct["status_code"] = toAct["status_code"]
fromAct["access_rules"] = toAct["access_rules"]
}
} | go | {
"resource": ""
} |
q180859 | LocatorFunc | test | func LocatorFunc(attributes []*gen.Attribute, name string) string {
hasLinks := false
for _, a := range attributes {
if a.FieldName == "Links" {
hasLinks = true
break
}
}
if !hasLinks {
return ""
}
return `for _, l := range r.Links {
if l["rel"] == "self" {
return api.` + name + `Locator(l["href"])
}
}
return nil`
} | go | {
"resource": ""
} |
q180860 | ParseRoute | test | func ParseRoute(moniker string, routes []string) (pathPatterns []*gen.PathPattern) {
// :(((( some routes are empty
var paths []string
var method string
switch moniker {
case "Deployments#servers":
method, paths = "GET", []string{"/api/deployments/:id/servers"}
case "ServerArrays#current_instances":
method, paths = "GET", []string{"/api/server_arrays/:id/current_instances"}
case "ServerArrays#launch":
method, paths = "POST", []string{"/api/server_arrays/:id/launch"}
case "ServerArrays#multi_run_executable":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_run_executable"}
case "ServerArrays#multi_terminate":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_terminate"}
case "Servers#launch":
method, paths = "POST", []string{"/api/servers/:id/launch"}
case "Servers#terminate":
method, paths = "POST", []string{"/api/servers/:id/terminate"}
default:
for _, route := range routes {
bound := routeRegexp.FindStringIndex(route)
match := route[0:bound[0]]
method = strings.TrimRight(match[0:7], " ")
path := strings.TrimRight(match[7:], " ")
path = strings.TrimSuffix(path, "(.:format)?")
if isDeprecated(path) || isCustom(method, path) {
continue
}
paths = append(paths, path)
}
}
pathPatterns = make([]*gen.PathPattern, len(paths))
for i, p := range paths {
rx := routeVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(p), `/([^/]+)`)
rx = fmt.Sprintf("^%s$", rx)
pattern := gen.PathPattern{
HTTPMethod: method,
Path: p,
Pattern: routeVariablesRegexp.ReplaceAllLiteralString(p, "/%s"),
Regexp: rx,
}
matches := routeVariablesRegexp.FindAllStringSubmatch(p, -1)
if len(matches) > 0 {
pattern.Variables = make([]string, len(matches))
for i, m := range matches {
pattern.Variables[i] = m[1]
}
}
pathPatterns[i] = &pattern
}
return
} | go | {
"resource": ""
} |
q180861 | isDeprecated | test | func isDeprecated(path string) bool {
return strings.Contains(path, "/api/session") && !strings.Contains(path, "/api/sessions")
} | go | {
"resource": ""
} |
q180862 | isQueryParam | test | func isQueryParam(a, n string) bool {
return n == "view" || n == "filter" || (a == "index" && (n == "with_deleted" || n == "with_inherited" || n == "latest_only" || n == "lineage"))
} | go | {
"resource": ""
} |
q180863 | isPathParam | test | func isPathParam(p string, pathPatterns []*gen.PathPattern) bool {
for _, pattern := range pathPatterns {
for _, v := range pattern.Variables {
if p == v {
return true
}
}
}
return false
} | go | {
"resource": ""
} |
q180864 | fetchAuditEntries | test | func fetchAuditEntries(client *cm15.API, filterEmail string) ([]*cm15.AuditEntry, error) {
auditLocator := client.AuditEntryLocator("/api/audit_entries")
var apiParams = rsapi.APIParams{"filter": []string{"user_email==" + filterEmail}}
auditEntries, err := auditLocator.Index(
tomorrow(), // End date
"100", // Limit
yesterday(), // Start date
apiParams,
)
if err != nil {
return auditEntries, err
}
return auditEntries, nil
} | go | {
"resource": ""
} |
q180865 | formatTime | test | func formatTime(tm time.Time) string {
year, month, date := tm.Date()
return time.Date(year, month, date, 0, 0, 0, 0, time.UTC).Format("2006/01/02 15:04:05 -0700")
} | go | {
"resource": ""
} |
q180866 | printAudits | test | func printAudits(entries []*cm15.AuditEntry) {
for _, a := range entries {
fmt.Printf("[%v] <%v>: %v\n", a.UpdatedAt, a.UserEmail, a.Summary)
}
} | go | {
"resource": ""
} |
q180867 | extractUnique | test | func extractUnique(oldEntries, newEntries []*cm15.AuditEntry) []*cm15.AuditEntry {
var uniqueEntries = make([]*cm15.AuditEntry, 0)
var oldHrefs = make([]string, len(oldEntries))
for i, e := range oldEntries {
oldHrefs[i] = getHref(e)
}
for _, newEntry := range newEntries {
if !stringInSlice(getHref(newEntry), oldHrefs) {
uniqueEntries = append(uniqueEntries, newEntry)
}
}
return uniqueEntries
} | go | {
"resource": ""
} |
q180868 | getHref | test | func getHref(entry *cm15.AuditEntry) string {
var href string
for _, link := range entry.Links {
if link["rel"] == "self" {
href = link["href"]
break
}
}
return href
} | go | {
"resource": ""
} |
q180869 | fail | test | func fail(format string, v ...interface{}) {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Println(fmt.Sprintf(format, v...))
os.Exit(1)
} | go | {
"resource": ""
} |
q180870 | parameters | test | func parameters(a *gen.Action) string {
var m = a.MandatoryParams()
var hasOptional = a.HasOptionalParams()
var countParams = len(m)
if hasOptional {
countParams++
}
var params = make([]string, countParams)
for i, param := range m {
params[i] = fmt.Sprintf("%s %s", fixReserved(param.VarName), param.Signature())
}
if hasOptional {
params[countParams-1] = "options rsapi.APIParams"
}
return strings.Join(params, ", ")
} | go | {
"resource": ""
} |
q180871 | paramsInitializer | test | func paramsInitializer(action *gen.Action, location int, varName string) string {
var fields []string
var optionals []*gen.ActionParam
varName = fixReserved(varName)
for _, param := range action.Params {
if param.Location != location {
continue
}
if param.Mandatory {
name := param.Name
if location == 1 { // QueryParam
name = param.QueryName
}
fields = append(fields, fmt.Sprintf("\"%s\": %s,", name, fixReserved(param.VarName)))
} else {
optionals = append(optionals, param)
}
}
if len(fields) == 0 && len(optionals) == 0 {
return ""
}
var paramsDecl = fmt.Sprintf("rsapi.APIParams{\n%s\n}", strings.Join(fields, "\n\t"))
if len(optionals) == 0 {
return fmt.Sprintf("\n%s = %s", varName, paramsDecl)
}
var inits = make([]string, len(optionals))
for i, opt := range optionals {
name := opt.Name
if location == 1 { // QueryParam
name = opt.QueryName
}
inits[i] = fmt.Sprintf("\tvar %sOpt = options[\"%s\"]\n\tif %sOpt != nil {\n\t\t%s[\"%s\"] = %sOpt\n\t}",
opt.VarName, opt.Name, opt.VarName, varName, name, opt.VarName)
}
var paramsInits = strings.Join(inits, "\n\t")
return fmt.Sprintf("\n%s = %s\n%s", varName, paramsDecl, paramsInits)
} | go | {
"resource": ""
} |
q180872 | commandLine | test | func commandLine() string {
return fmt.Sprintf("$ %s %s", os.Args[0], strings.Join(os.Args[1:], " "))
} | go | {
"resource": ""
} |
q180873 | toVerb | test | func toVerb(text string) (res string) {
res = strings.ToUpper(string(text[0])) + strings.ToLower(text[1:])
if text == "GET" || text == "POST" {
res += "Raw"
}
return
} | go | {
"resource": ""
} |
q180874 | escapeBackticks | test | func escapeBackticks(d string) string {
elems := strings.Split(d, "`")
return strings.Join(elems, "` + `")
} | go | {
"resource": ""
} |
q180875 | AccountPreferenceLocator | test | func (api *API) AccountPreferenceLocator(href string) *AccountPreferenceLocator {
return &AccountPreferenceLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180876 | ApplicationLocator | test | func (api *API) ApplicationLocator(href string) *ApplicationLocator {
return &ApplicationLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180877 | EndUserLocator | test | func (api *API) EndUserLocator(href string) *EndUserLocator {
return &EndUserLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180878 | NotificationRuleLocator | test | func (api *API) NotificationRuleLocator(href string) *NotificationRuleLocator {
return &NotificationRuleLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180879 | UserPreferenceLocator | test | func (api *API) UserPreferenceLocator(href string) *UserPreferenceLocator {
return &UserPreferenceLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180880 | UserPreferenceInfoLocator | test | func (api *API) UserPreferenceInfoLocator(href string) *UserPreferenceInfoLocator {
return &UserPreferenceInfoLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180881 | LoadConfig | test | func LoadConfig(path string) (*ClientConfig, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var config ClientConfig
err = json.Unmarshal(content, &config)
if err != nil {
return nil, err
}
config.Password, err = Decrypt(config.Password)
if err != nil {
return nil, err
}
config.RefreshToken, err = Decrypt(config.RefreshToken)
return &config, err
} | go | {
"resource": ""
} |
q180882 | CreateConfig | test | func CreateConfig(path string) error {
config, _ := LoadConfig(path)
var emailDef, passwordDef, accountDef, hostDef, refreshTokenDef string
if config != nil {
yn := PromptConfirmation("Found existing configuration file %v, overwrite? (y/N): ", path)
if yn != "y" {
PrintSuccess("Exiting")
return nil
}
emailDef = fmt.Sprintf(" (%v)", config.Email)
accountDef = fmt.Sprintf(" (%v)", config.Account)
passwordDef = " (leave blank to leave unchanged)"
if config.LoginHost == "" {
config.LoginHost = "my.rightscale.com"
}
hostDef = fmt.Sprintf(" (%v)", config.LoginHost)
refreshTokenDef = " (leave blank to leave unchanged)"
} else {
config = &ClientConfig{}
}
fmt.Fprintf(out, "Account ID%v: ", accountDef)
var newAccount string
fmt.Fscanln(in, &newAccount)
if newAccount != "" {
a, err := strconv.Atoi(newAccount)
if err != nil {
return fmt.Errorf("Account ID must be an integer, got '%s'.", newAccount)
}
config.Account = a
}
fmt.Fprintf(out, "Login email%v: ", emailDef)
var newEmail string
fmt.Fscanln(in, &newEmail)
if newEmail != "" {
config.Email = newEmail
}
fmt.Fprintf(out, "Login password%v: ", passwordDef)
var newPassword string
fmt.Fscanln(in, &newPassword)
if newPassword != "" {
config.Password = newPassword
}
fmt.Fprintf(out, "API Login host%v: ", hostDef)
var newLoginHost string
fmt.Fscanln(in, &newLoginHost)
if newLoginHost != "" {
config.LoginHost = newLoginHost
}
fmt.Fprintf(out, "API Refresh Token%v: ", refreshTokenDef)
var newRefreshToken string
fmt.Fscanln(in, &newRefreshToken)
if newRefreshToken != "" {
config.RefreshToken = newRefreshToken
}
err := config.Save(path)
if err != nil {
return fmt.Errorf("Failed to save config: %s", err)
}
return nil
} | go | {
"resource": ""
} |
q180883 | fromAPI | test | func fromAPI(api *rsapi.API) *API {
api.FileEncoding = rsapi.FileEncodingJSON
api.Host = HostFromLogin(api.Host)
api.Metadata = GenMetadata
api.VersionHeader = "Api-Version"
return &API{api}
} | go | {
"resource": ""
} |
q180884 | HostFromLogin | test | func HostFromLogin(host string) string {
urlElems := strings.Split(host, ".")
hostPrefix := urlElems[0]
elems := strings.Split(hostPrefix, "-")
if len(elems) == 1 && elems[0] == "cm" {
// accommodates micromoo host inference, such as "cm.rightscale.local" => "selfservice.rightscale.local"
elems[0] = "governance"
} else if len(elems) < 2 {
// don't know how to compute this policy host; use the cm host
return host
} else {
elems[len(elems)-2] = "governance"
}
policyHostPrefix := strings.Join(elems, "-")
return strings.Join(append([]string{policyHostPrefix}, urlElems[1:]...), ".")
} | go | {
"resource": ""
} |
q180885 | AnalyzeParam | test | func (a *APIAnalyzer) AnalyzeParam(ec EvalCtx, p *Parameter) *gen.ActionParam {
location, ok := loc[p.In]
if !ok {
location = -1
}
ap := &gen.ActionParam{
Name: p.Name,
QueryName: p.Name,
Description: cleanDescription(p.Description),
VarName: toVarName(p.Name),
Location: location,
Mandatory: p.Required,
NonBlank: p.Required || p.Pattern != "",
Regexp: p.Pattern,
ValidValues: p.Enum,
}
if p.Schema != nil {
ap.Type = a.typeForRef(ec, p.Schema)
} else {
ap.Type = basicType(p.Type)
}
return ap
} | go | {
"resource": ""
} |
q180886 | AnalyzeAttribute | test | func (a *APIAnalyzer) AnalyzeAttribute(name, query string, attr map[string]interface{}) (*gen.ActionParam, error) {
param := gen.ActionParam{Name: name, QueryName: query, VarName: toVarName(name)}
if d, ok := attr["description"]; ok {
param.Description = removeBlankLines(d.(string))
}
if r, ok := attr["required"]; ok {
if r.(bool) {
param.Mandatory = true
}
}
if options, ok := attr["options"]; ok {
opts, ok := options.(map[string]interface{})
if ok {
for n, o := range opts {
switch n {
case "max":
param.Max = int(o.(float64))
case "min":
param.Min = int(o.(float64))
case "regexp":
param.Regexp = o.(string)
}
}
}
}
if values, ok := attr["values"]; ok {
param.ValidValues = values.([]interface{})
}
t := attr["type"].(map[string]interface{})
dataType, err := a.AnalyzeType(t, query)
if err != nil {
return nil, err
}
param.Type = dataType
switch dataType.(type) {
case *gen.ArrayDataType:
param.QueryName += "[]"
}
return ¶m, nil
} | go | {
"resource": ""
} |
q180887 | AnalyzeType | test | func (a *APIAnalyzer) AnalyzeType(typeDef map[string]interface{}, query string) (gen.DataType, error) {
n, ok := typeDef["name"].(string)
if !ok {
n = "Struct" // Assume inline struct (e.g. payload types)
}
if strings.HasSuffix(n, "FileUpload") {
// A little bit hacky but this is to make upload work with resticle
// The idea is that a type named "FileUpload" is assumed to define a multipart
// request with a file part.
// The type must define a "name" and "filename" string fields.
t, ok := a.RawTypes[n]
if !ok {
return nil, fmt.Errorf("Unknown type %s for %s", n, prettify(typeDef))
}
attrs, ok := t["attributes"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no attributes", n, prettify(typeDef))
}
mattrs, ok := attrs.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: basic type", n, prettify(typeDef))
}
_, ok = mattrs["name"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no name", n, prettify(typeDef))
}
_, ok = mattrs["filename"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no filename", n, prettify(typeDef))
}
return &gen.UploadDataType{TypeName: n}, nil
}
if isBuiltInType(n) {
n = "String"
}
var dataType gen.DataType
switch n {
case "Integer":
i := gen.BasicDataType("int")
dataType = &i
case "Float":
f := gen.BasicDataType("float64")
dataType = &f
case "String":
s := gen.BasicDataType("string")
dataType = &s
case "Boolean":
b := gen.BasicDataType("bool")
dataType = &b
case "Object":
o := gen.BasicDataType("interface{}")
dataType = &o
case "DateTime":
t := gen.BasicDataType("*time.Time") // Need pointer for case where value is null
a.descriptor.NeedTime = true
dataType = &t
case "Collection", "Ids":
member, ok := typeDef["member_attribute"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Missing \"member_attribute\" for %s", prettify(typeDef))
}
elemType, err := a.AnalyzeAttribute(n+"Member", query+"[]", member)
if err != nil {
return nil, fmt.Errorf("Failed to compute type of \"member_attribute\": %s", err)
}
dataType = &gen.ArrayDataType{elemType}
case "Struct":
attrs, ok := typeDef["attributes"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Failed to retrieve attributes of struct for %s", prettify(typeDef))
}
obj, err := a.CreateType(query, attrs)
if err != nil {
return nil, err
}
dataType = obj
case "Hash":
keys, ok := typeDef["keys"].(map[string]interface{})
if !ok {
dataType = new(gen.EnumerableDataType)
} else {
obj, err := a.CreateType(query, keys)
if err != nil {
return nil, err
}
dataType = obj
}
default:
// First check if we already analyzed that type
if t := a.Registry.GetNamedType(n); t != nil {
return t, nil
}
// No then analyze it
t, ok := a.RawTypes[n]
if !ok {
return nil, fmt.Errorf("Unknown type %s for %s", n, prettify(typeDef))
}
attrs, ok := t["attributes"]
if !ok {
// No attribute, it's a string
s := gen.BasicDataType("string")
dataType = &s
} else {
att := attrs.(map[string]interface{})
obj := a.Registry.CreateNamedType(n)
obj.Fields = make([]*gen.ActionParam, len(att))
for idx, an := range sortedKeys(att) {
at := att[an]
aq := fmt.Sprintf("%s[%s]", query, an)
ap, err := a.AnalyzeAttribute(an, aq, at.(map[string]interface{}))
if err != nil {
return nil, err
}
obj.Fields[idx] = ap
}
// We're done
dataType = obj
}
}
return dataType, nil
} | go | {
"resource": ""
} |
q180888 | CreateType | test | func (a *APIAnalyzer) CreateType(query string, attributes map[string]interface{}) (*gen.ObjectDataType, error) {
name := inflect.Camelize(bracketRegexp.ReplaceAllLiteralString(query, "_") + "_struct")
obj := a.Registry.CreateInlineType(name)
obj.Fields = make([]*gen.ActionParam, len(attributes))
for idx, an := range sortedKeys(attributes) {
at := attributes[an]
var childQ string
if query == "payload" {
childQ = an
} else {
childQ = fmt.Sprintf("%s[%s]", query, an)
}
att, err := a.AnalyzeAttribute(an, childQ, at.(map[string]interface{}))
if err != nil {
return nil, fmt.Errorf("Failed to compute type of attribute %s: %s", an, err)
}
obj.Fields[idx] = att
}
return obj, nil
} | go | {
"resource": ""
} |
q180889 | Ref | test | func (d *Doc) Ref(r Ref) *Definition {
if refIF, ok := r["$ref"]; ok {
refKey := strings.TrimPrefix(refIF.(string), "#/definitions/")
return d.Definitions[refKey]
}
return nil
} | go | {
"resource": ""
} |
q180890 | Type | test | func (r Ref) Type() string {
if _, ok := r["$ref"]; ok {
return "object"
}
if refIF, ok := r["type"]; ok {
return refIF.(string)
}
return ""
} | go | {
"resource": ""
} |
q180891 | Required | test | func (r Ref) Required() []string {
if refIF, ok := r["required"]; ok {
return refIF.([]string)
}
return []string{}
} | go | {
"resource": ""
} |
q180892 | ID | test | func (r Ref) ID() string {
if refIF, ok := r["$ref"]; ok {
return strings.TrimPrefix(refIF.(string), "#/definitions/")
}
return ""
} | go | {
"resource": ""
} |
q180893 | Service | test | func (ep *Endpoint) Service() string {
if len(ep.Tags) > 0 {
return ep.Tags[0]
}
if len(ep.OperationID) > 0 {
return strings.Split(ep.OperationID, "#")[0]
}
return ""
} | go | {
"resource": ""
} |
q180894 | Method | test | func (ep *Endpoint) Method() string {
if strings.Contains(ep.OperationID, "#") {
return strings.Split(ep.OperationID, "#")[1]
}
return ""
} | go | {
"resource": ""
} |
q180895 | NewTypeRegistry | test | func NewTypeRegistry() *TypeRegistry {
return &TypeRegistry{
NamedTypes: make(map[string]*gen.ObjectDataType),
InlineTypes: make(map[string][]*gen.ObjectDataType),
}
} | go | {
"resource": ""
} |
q180896 | GetNamedType | test | func (reg *TypeRegistry) GetNamedType(name string) *gen.ObjectDataType {
return reg.NamedTypes[toGoTypeName(name)]
} | go | {
"resource": ""
} |
q180897 | CreateNamedType | test | func (reg *TypeRegistry) CreateNamedType(name string) *gen.ObjectDataType {
goName := toGoTypeName(name)
obj := gen.ObjectDataType{TypeName: goName}
if _, ok := reg.NamedTypes[goName]; ok {
panic("BUG: Can't create two named types with same name....")
}
reg.NamedTypes[goName] = &obj
return &obj
} | go | {
"resource": ""
} |
q180898 | CreateInlineType | test | func (reg *TypeRegistry) CreateInlineType(name string) *gen.ObjectDataType {
goName := toGoTypeName(name)
obj := gen.ObjectDataType{TypeName: goName}
reg.InlineTypes[goName] = append(reg.InlineTypes[goName], &obj)
return &obj
} | go | {
"resource": ""
} |
q180899 | FinalizeTypeNames | test | func (reg *TypeRegistry) FinalizeTypeNames(d *gen.APIDescriptor) {
for n, named := range reg.NamedTypes {
reg.InlineTypes[n] = append(reg.InlineTypes[n], named)
}
d.FinalizeTypeNames(reg.InlineTypes)
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.